Silverlight ComboBox TwoWay Binding failure
This is not a question but an answer, and the answer may seem very obvious to some but I thought it might still be useful to others!
I posted this first to create a post. The scenario is in the an开发者_StackOverflow社区swer.
I had a MainView/MainViewModel and a SearchView/SearchViewModel.
I had a ComboBox on the MainView populated with a list of 'Gender' objects (bound to
ObservableCollection<Gender> Genders
in the MainViewModel)
The MainViewModel had a property of type Person which in turn had a property of type Gender. The Gender object had properties of ID and Description (the description was displayed in the combo).
The SelectedItem attribute of the ComboBox was bound to 'Person.Gender' in TwoWay mode.
When using this to set the value of Gender on a new Person object everything was fine. The user was then allowed to do a search for an existing Person. I retrieved data based on parameters and created a list of Person objects and passed them tp the SearchViewModel via MVVM Light Toolkit's Messenger. These were then displayed in a grid on the SearchView modally. When the user chose a Person this (SelectedPerson) was passed back from the SearchViewModel to the MainViewModel, again using MVVM Light's Messenger.
This is now where I was stuck for a while. I coded
Person.Gender = SelectedPerson.Gender
and expected the ComboBox to be updated with the correct gender but it wasn't.
I searched for binding issues and found the one about having the XAML ItemsSource and SelectedItems attributes in the right order. I tried creating a new Gender e.g. Person.Gender = new Gender { ID=SelectedPerson.Gender.ID... etc. but this did not work.
Then it occurred to me that, although the Gender in the ComboBox had exactly the same properties as the Gender in the SelectedPerson object it didn't make it EQUAL and I was thinking in human terms and not programming terms. The Gender object that DID equal the one on the ComboBox was in the collection that the ComboBox was bound to (i.e. ObservableCollection Genders). Therefore, to get it I did this
if (SelectedPerson.Gender != null)
{
foreach (Gender g in Genders)
{
if (SelectedPerson.Gender.ID == g.ID)
{
Person.Gender = g;
break;
}
}
}
As I said this is probably obvious to some but when I was originally stuck I did not find any solution that looked like this as noone described a scenario like this. I would hazard a guess that in some case the scenario was similar but the questioner didn't realize, i.e. equality of objects.
精彩评论