Silverlight 4, combobox databinding problem
Posted
by synergetic
on Stack Overflow
See other posts from Stack Overflow
or by synergetic
Published on 2010-06-18T06:40:31Z
Indexed on
2010/06/18
6:43 UTC
Read the original article
Hit count: 654
In my Silverlight 4 app, CustomerView (UserControl) shows Customer object as it's DataContext. Customer object has IndustryCode string property. I created combobox called cboIndustryCode and bind it to the IndustryCode property the following way:
<ComboBox x:Name="cboIndustryCode"
SelectedValue="{Binding IndustryCode, Mode=TwoWay}"
...
/>
In code-behind I populate cboIndustryCode with List of Industry object, which has Code and Name properties:
cboIndustryCode.ItemsSource = industries; //which is of List<Industry> type
Now, to show everything properly, in XAML I added the following:
<ComboBox x:Name="cboIndustryCode"
SelectedValue="{Binding IndustryCode, Mode=TwoWay}"
DisplayMemberPath="Name"
SelectedValuePath="Code"
...
/>
So, when I get a customer class from my data layer and set the DataContext to this customer instance, the cboIndustryCode properly displays industry name. But, then I edit customer (not necessarily IndustryCode) and save the object (which resets DataContext = new Customer()) and retrieve the customer again from database, and I see that cboIndustryCode no longer working. It just displays nothing, and if I select new value from the list, it does not update underlying customer object's IndustryCode property. The problem goes away, if I put the following code in the place where I set DataContext to a instance of customer, retrieved from database:
Binding binding = new Binding("IndustryCode");
binding.Mode = BindingMode.TwoWay;
cboIndustryCode.SetBinding(ComboBox.SelectedValueProperty, binding);
So, in short, combobox's binding is reset somehow every time I save my data. Can someone tell me the reason?
© Stack Overflow or respective owner