2
votes

This issue that is occurring is that whenever the WPF ComboBox ItemsSource property is changed the SelectedItem property is being set to null.

Requirements to recreate issue:

  1. Original ItemsSource is a collection of objects that ARE NOT value types
  2. SelectedValue is bound to some property
  3. SelectedValuePath is set
  4. SelectedItem is some item in the original ItemsSource
  5. New ItemsSource is a collection of objects of the same type as the original
  6. ItemsSource that does not contain a reference to the same object in memory as the current SelectedItem

Actually I want to bind Combobox in Datagrid templete, Combobox collection exist in view model, When I change first column property other rows combo box item became null.

How can i solve this issue?

1
What do you expect it to be set to if the object is no longer in the list? You'll need to check the SelectedItem after you change the list, and if it is null, pick a new item to set it to.dbugger
+1 for what dbugger said. As soon as you change the item source, the original item no longer exists as part of the item collection. What exactly are you trying to accomplish? Normally, selecting an item from a Combobox does not cause that combobox to change itemsource; rather, a separate combobox or list will be generated or populated as a result of the selection. At least, that's a more normal UI function.DiscipleMichael
Actually I want to bind Combobox in Datagrid templete, Combobox collection exist in view model, When I change first column property other rows combo box item became null.Sam Alex

1 Answers

3
votes

The SelectedItem object MUST be within the ItemsSource collection.

If you want to assign a new SelectedItem from the new ItemsSource collection, which matches a property on the previous SelectedItem then save the property value before changing ItemsSource and find the matching item.

var id = ((MyType)MyCombo.SelectedItem).Id;

MyCombo.ItemsSource = MyNewList;

MyCombo.SelectedItem = MyNewList.FirstOrDefault(x => x.Id == id);