I was following the tutorial Binding a comboBox to an Enum and came out with this XML code:
<ComboBox
DisplayMemberPath="Key"
SelectedValuePath="Value"
ItemsSource="{Binding VolumeLevelList}"
SelectedValue="{Binding SelectedVolumeLevel, ValidatesOnDataErrors=True, Mode=TwoWay}"
Height="23" HorizontalAlignment="Left" Margin="189,70,0,0"
VerticalAlignment="Top" Width="120" />
I'm looking for a way to select a default choice, something like
SelectedIndex="0"
But thats not working..
I downloaded the code from tutorial and noticed that something is missing. In the MainViewModel
, INotifyPropertyChanged
is correctly implemented, however, the SelectedVolumeLevel
property doesn't call the RaisePropertyChanged()
method on set
. What this means is that when you update the combobox, the source doesn't get updated. The reason your SelectedIndex
doesn't work is because the SelectedValue
is already set and bound to the source. To fix this, add a backing field to your MainViewModel
like this:
private VolumeLevel selectedVolumeLevel = VolumeLevel.LowVolume; // Default is set to low
Then change the SelectedVolumeLevel
property to this:
public VolumeLevel SelectedVolumeLevel
{
get { return selectedVolumeLevel; }
set { selectedVolumeLevel = value; RaisePropertyChanged("SelectedVolumeLevel"); }
}
Now every time the selected item in the combobox is changed, the source properly gets updated. This should also fix your default choice issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With