Friday, 28 October 2011

MVVM Combo Box Options

You have three options:

Option 1
1.Instead of adding ComboBoxItem items add String items:
<ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
SelectedItem="{Binding fruit, Mode=TwoWay}">
<sys:String>apple</sys:String>
<sys:String>orange</sys:String>
<sys:String>grape</sys:String>
<sys:String>banana</sys:String>
</ComboBox>
Option 2
Instead of SelectedItem bind to SelectedValue and specify SelectedValuePath as Content:
<ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
SelectedValue="{Binding fruit, Mode=TwoWay}"
SelectedValuePath="Content">
<ComboBoxItem>apple</ComboBoxItem>
<ComboBoxItem>orange</ComboBoxItem>
<ComboBoxItem>grape</ComboBoxItem>
<ComboBoxItem>banana</ComboBoxItem>
</ComboBox>
Option 3
Do not specify items directly in XAML, but use 
ItemsSource property to bind to a collection of strings:
<ComboBox HorizontalAlignment="Left" Height="22" Margin="24,97,0,0" VerticalAlignment="Top" Width="83"
ItemsSource="{Binding Fruits}"
SelectedItem="{Binding fruit, Mode=TwoWay}"/>

Thanks To:
Pavlo Glazkov
Posted at

http://stackoverflow.com/questions/5159708/weird-databinding-issues-in-wpf-combobox