简体   繁体   中英

WPF `ComboBox` ItemsSource property is changed the SelectedItem property is being set to null

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM