Anonymous
Anonymous

Reputation: 9658

Silverlight 4 ComboBox SelectedValue not working when ItemsSource changed

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 want to know how can I fixed these problems?

Upvotes: 1

Views: 6217

Answers (3)

HAIJIA.HOU
HAIJIA.HOU

Reputation: 21

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>

Upvotes: 2

Anonymous
Anonymous

Reputation: 9658

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

Upvotes: 0

Jaans
Jaans

Reputation: 4638

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

Upvotes: 0

Related Questions