I am developing application with WPF, following MVVM pattern using MVVMLight. I have an issue with ComboBox that I do not know how to resolve.
ItemsSource for ComboBox is provided by service in application. SelectedValue is set using Binding to VM's property:
<ComboBox ItemsSource="{Binding AllValues}" SelectedValue="{Binding SelectedValue, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" DisplayMemberPath="Key" IsSynchronizedWithCurrentItem="True"/>
public ObservableCollection<ComboBoxValue> AllValues { get; set; }
public ComboBoxValue SelectedValue { get; set; }`enter code here`
If I update SelectedValue
in VM to some value that exists in AllValues
, everything is ok, ComboBox selection is updated, SelectionChanged
event is fired. However if I set SelectedValue
in VM to some value that does not exist in AllValues
, nothing happens with ComboBox, no event is fired and I could not find method that I can override to handle the situation. Final result is that ComboBox still shows old value, different than value of property that it is bound to.
I would like to handle this and change value of SelectedItem
when this happens. This can be easily done in VM, but it is not right place to handle this.
SelectionChanged
event instead of during setting, or even in setter of SelectedValue? – sTrenatAllValues
). You want to edit some data, you load data from server asynchronously and setSelectedValue
to some value previously saved. IfAllValues
don't contain that value anymore, you end up in situation that ComboBox does not show anything selected, andSelectedItem
has some value. Save changes without touching ComboBox and you saved different data than what user saw. – NemanjaJif(!AllValues.Contains(SelectedValue)) AllValues.Add(SelectedValue);
in setter of SelectedValue? – sTrenat