WPF - MVVM - ComboBox SelectedItem

前端 未结 4 642
春和景丽
春和景丽 2021-02-07 05:21

I have ViewModel(implemented INotifyPropertyChanged) in the background and class Category which has only one property of type string

4条回答
  •  情深已故
    2021-02-07 05:46

    The category you are setting in this line -

    NodeCategory = some_list_of_other_objects.Category;
    

    and one present in your Categories collection(ItemsSource="{Binding Categories}") should be referring to same object. If they are not then SelectedItem won't work.

    Solution 1 -

    You can also try to use SelectedValuePath like this -

    
    

    and in code you can do something like this -

    private string _NodeCategory;
    public string NodeCategory
    {
        get
        {
            return _NodeCategory;
        }
        set
        {
            _NodeCategory = value;
            OnPropertyChanged("NodeCategory");
        }
    }
    

    and set selected item like this -

    NodeCategory = some_list_of_other_objects.Category.Name;
    

    and use selected value like this -

    Category selectedCategory = 
       some_list_of_other_objects.FirstOrDefault(cat=> cat.Name == NodeCategory);
    

    or

    Category selectedCategory = 
       Categories.FirstOrDefault(cat=> cat.Name == NodeCategory);
    

    Solution 2 -

    Another possible solution can be -

    NodeCategory = 
      Categories.FirstOrDefault(cat=> cat.Name == some_list_of_other_objects.Category.Name);
    

    this way your NodeCategory property will have the reference of an object in Categories collection and SelectedItem will work.

提交回复
热议问题