Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wpf default comboBox item when data-binding

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..

like image 875
drtf Avatar asked Oct 21 '22 09:10

drtf


1 Answers

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.

like image 146
PoweredByOrange Avatar answered Oct 28 '22 21:10

PoweredByOrange