I would want to update the following combobox selected item:
<ComboBox ItemsSource="{Binding Path=DictUsers, UpdateSourceTrigger=PropertyChanged}" DisplayMemberPath="Key" SelectedValuePath="Value" SelectionChanged="ComboUser_SelectionChanged" SelectedValue="{Binding Edit.ProtLevel, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
The ItemsSource, DictUsers, comes from a dictionary:
DictUsers = new Dictionary<string, int>();
DictUsers.Add(string.Empty, 0);
foreach (cUser user in App.Users)
DictUsers.Add(user.Name, user.ShowLevel);
I cannot access directly to the ComboBox as it's inside a datatemplate, so I tought up update the binded value (Edit.ProtLevel):
// Test
Edit.ProtLevel = 5;
But the combobox doesn't update itself, which means that the selected items doesn't change. What's wrong?
For your binding to work correctly, the bound property should be a DependencyProperty
or be inside of a class that implements INotifyPropertyChanged
, something like this should work:
public class Edit : INotifyPropertyChanged {
private int _protLevel;
public int ProtLevel {
get => _protLevel;
set {
if (_protLevel != (_protLevel = value)) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ProtLevel)));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
You can read the binding documentation here.
And a simple INotifyPropertyChanged
implementation here.