I am using WPF with databinding. I have a Combobox bound to a list of strings. I want the selected item in the list to set a field in my View Model. However, I sometimes want to override the user's selection and re-set the selected value in the Combobox but I don't seem to be able to do that.
Here's the View Model code:
public class SettingsViewModel : INotifyPropertyChanged
{
public enum RateTypes
{
[Description("128Hz")]
Hz128 = 4,
[Description("256Hz")]
Hz256 = 6,
[Description("400Hz")]
Hz400 = 7,
[Description("512Hz")]
Hz512 = 8,
[Description("600Hz")]
Hz600 = 9
}
RateTypes m_SelectedRate;
List<string> RateOptions = ((RateTypes [])Enum.GetValues(typeof(RateTypes)))
.Select(o => o.Description())
.ToList();
public string SelectedRate
{
get {return m_SelectedRate.Description();}
set
{
if (value == RateType.Hz256)
{
MessageBox.Show("256Hz not an option with your system");
m_SelectedRate= IMURate.Hz400;
}
else
{
m_SelectedRate = value;
}
OnPropertyChanged(nameof(SelectedRate));
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyChanged)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyChanged);
handler(this, e);
}
}
}
and the XAML has:
<ComboBox Grid.SelectedItem="{Binding SelectedRate, Mode=TwoWay}" ItemsSource="{Binding RateOptions}">
However, when I select 256Hz in the GUI, the value displayed stays as 256Hz instead of changing to 400Hz. If I call OnPropertyChanged(SelectedRate)
from a separate function, the value does change.
I've tried using SelectedValue
and UpdateSourceTrigger
but can't find anything that works.
Any ideas?