I have ViewModel
(implemented INotifyPropertyChanged
) in the background and class Category
which has only one property of type string
. My ComboBox SelectedItem is bind to an instance of a Category. When i change the value of instance, SelectedItem is not being updated and Combobox is not changed.
EDIT: code
Combobox:
<ComboBox x:Name="categoryComboBox" Grid.Column="1" Grid.Row="3" Grid.ColumnSpan="2"
Margin="10" ItemsSource="{Binding Categories}"
DisplayMemberPath="Name" SelectedValue="{Binding NodeCategory, Mode=TwoWay}"/>
Property:
private Category _NodeCategory;
public Category NodeCategory
{
get
{
return _NodeCategory;
}
set
{
_NodeCategory = value;
OnPropertyChanged("NodeCategory");
}
}
[Serializable]
public class Category : INotifyPropertyChanged
{
private string _Name;
[XmlAttribute("Name")]
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
OnPropertyChanged("Name");
}
}
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
}
and what I am trying is: when I set
NodeCategory = some_list_of_other_objects.Category;
to have that item selected in Combobox
with appropriate DisplayMemberPath
The category you are setting in this line -
and one present in your Categories collection(
ItemsSource="{Binding Categories}"
) should be referring to same object. If they are not thenSelectedItem
won't work.Solution 1 -
You can also try to use
SelectedValuePath
like this -and in code you can do something like this -
and set selected item like this -
and use selected value like this -
or
Solution 2 -
Another possible solution can be -
this way your NodeCategory property will have the reference of an object in Categories collection and
SelectedItem
will work.Your XAML needs a couple of modifications but I think the real problem is with the code you have posted which I don't think is telling the full story. For starters, your combobox
ItemSource
is bound to a property called Categories but you do not show how this property is coded or how yourNodeCategory
property is initially synced with the item.Try using the following code and you will see that the selected item is kept in sync as the user changes the value in the combobox.
XAML
Code-behind
From my little example:
Note: This is setting just a string (or a category from another list), but the basics should be same here:
Basically this is done:
Here is my XAML:
and in the ViewModel of the Window
With the help of this little class:
And this Item ViewModel