Updating a ComboBox SelectedItem from code behind

后端 未结 2 1620
离开以前
离开以前 2021-01-24 11:39

im having a View with a ComboBox bound to my viewModel property. Everything works fine but i actually want to reuse my View and need to update the controls with a given value.

2条回答
  •  遇见更好的自我
    2021-01-24 11:49

    By default, WPF compares the SelectedItem by reference, not by value. That means if the SelectedItem isn't the exact same object in memory as the item in your ItemsSource, then the comparisom will return false and the item will not get selected.

    For example, this will probably not work

    MyCollection = new ObservableCollection(DAL.GetUsers());
    SelectedUser = DAL.GetUser(1);
    

    however this would:

    MyCollection = new ObservableCollection(DAL.GetUsers());
    SelectedUser = MyCollection.FirstOrDefault(p => p.Id == 1);
    

    That's because the 2nd example sets the SelectedUser to an item that actually exists in MyCollection, while the 1st example might not. Even if the data is the same, they reference different objects in memory.

    If your selected item doesn't reference the same item in memory as your ItemsSource item, then either use SelectedValue and SelectedValuePath to bind your ComboBox's default selection, or overwrite the .Equals() method of your class to return true if the data in the objects being compared is the same.

    public override bool Equals(object obj)
    {
        if (obj == null || !(obj == MyClass))
            return false; 
    
        return ((MyClass)obj).Id == this.Id);
    }
    

提交回复
热议问题