Updating a ComboBox SelectedItem from code behind

后端 未结 2 1599
离开以前
离开以前 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<User>(DAL.GetUsers());
    SelectedUser = DAL.GetUser(1);
    

    however this would:

    MyCollection = new ObservableCollection<User>(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);
    }
    
    0 讨论(0)
  • 2021-01-24 12:02

    It may happen if you do not Items collection doesn't contain an item equal to SelectedItem. Check whether you have such an item (it may be that you just forgot to overload Equals in your class and it uses references comparison)

    0 讨论(0)
提交回复
热议问题