开发者

Silverlight 4 ComboBox SelectedValue not working when ItemsSource changed

开发者 https://www.devze.com 2023-01-26 09:46 出处:网络
I have 2 properties in ViewModel class, EmployeeList and Employee. EmployeeList is dynamic property, that being said, this property can change at run time. ViewModel class source code is below:

I have 2 properties in ViewModel class, EmployeeList and Employee. EmployeeList is dynamic property, that being said, this property can change at run time. ViewModel class source code is below:

public class SampleViewModel
{
    public ObservableCollection<Employee> EmployeeList { get; set; }
    public Employee { get { ... } set { ... } }
}

View has set its ItemsSource and SelectedValue property to EmployeeList and Employee respectively.

ItemsSource="{Binding EmployeeList, Mode=TwoWay}"
SelectedValue="{Binding Employee, Mode=TwoWay}"

Everythings work well except EmployeeList has changed and Employee does not exist in EmployeeList, step of scenarios is below.

  1. EmployeeList has 2 employee, Mr. A and Mr. B and SelectedValue is Mr. A
  2. EmployeeList has changed to Mr. B and Mr. C, after this time SelectedValue is not work any more. If I set Employee on ViewModel and NotifyPropertyChanged this value won't update on UI or if I selected new Employee from UI this value won't update on ViewModel, the bottom line is View and ViewModel was disconnected since EmployeeList has changed and Employee does not exist in that list.

I开发者_如何学C want to know how can I fixed these problems?


I guess you have to bind the combobox like below:

<ComboBox Grid.Row="5" Grid.Column="1" ItemsSource="{Binding Path=Employee,Mode=TwoWay}">
  <DataTemplate>
    <StackPanel>
       <TextBlock Height="8" HorizontalAlignment="Center" Text="{Binding Path=MR.A}"/>
       <TextBlock Height="8" HorizontalAlignment="Center" Text="{Binding Path=MR.B}"/>
     </StackPanel>
  </DataTemplate>
</ComboBox>


I too have major issues with the Silverlight 4 ComboBox and SelectedValue bindings. Strangely, using SelectedItem for binding works very well, but that isn't always feasible, especially when using domain objects and FK Id type lookups.

Have a look at my post over at the CSLA forums - it resolve most timing and binding issues when using selected value.

http://forums.lhotka.net/forums/p/9786/45971.aspx

Hope that helps


I can solved this problem by solution from Silverlight ComboBox Sample for RIA Services.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号