Reputation: 2620
I have a simple combo :
<ComboBox x:Name="testCombo" SelectedValue="{Binding State, Mode=TwoWay}" VerticalAlignment="Center" HorizontalAlignment="Center" MinWidth="100">
<ComboBoxItem>OPEN</ComboBoxItem>
<ComboBoxItem>CLOSED</ComboBoxItem>
</ComboBox>
That state is just a string property with INotifyPropertyChanged implemented.
private string state;
public string State
{
get { return state; }
set
{
state = value;
OnPropertyChanged("State");
}
}
What i want to achieve is, when that State string property is initially set to "OPEN", when my window loads, the ComboBox to set it's initial item as "OPEN".
I also tried to attach a converter there:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ComboBoxItem cbi = new ComboBoxItem();
cbi.Content = value as string;
return cbi;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value as ComboBoxItem).Content;
}
With this, my State string property will be fine populated, but the ComboBox won't get to the desired initial state.
Upvotes: 0
Views: 176
Reputation: 33384
ComboBoxItem
is not compared by content but by reference and the instance you create in converter is not the same instance displayed in ComboBox
so they will never be equal. What you can do is set ItemsSource
as list of strings and bind SelectedItem
directly to string property without any converter
<ComboBox SelectedItem="{Binding State, Mode=TwoWay}" x:Name="testCombo">
<ComboBox.ItemsSource>
<x:Array Type="{x:Type sys:String}">
<sys:String>OPEN</sys:String>
<sys:String>CLOSED</sys:String>
</x:Array>
</ComboBox.ItemsSource>
</ComboBox>
you'll need to add sys
namespace to your XAML as well
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Upvotes: 2