Reputation: 59
I am doing an application in MVVM and I am new at it... I have a boolean field and want to show a combobox to user with items Yes/No but when user selects it, but in data context values are 1 and 0. i have the following code:
<TextBlock Grid.Row="2" Grid.Column="2" Text="Batch Flag" Margin="5,0,0,0" />
<ComboBox Grid.Row="2" Grid.Column="3" x:Name="cboBtchFlg" SelectedItem="{Binding SelectedADM_M022.BtchFlg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Margin="5,0,0,2" Background="Transparent">
<ComboBoxItem Tag="1">True</ComboBoxItem>
<ComboBoxItem Tag="0">False</ComboBoxItem>
</ComboBox>
Upvotes: 2
Views: 1377
Reputation: 441
You could use a converter. If the view model property is a bool, and this is bound to the SelectedIndex property of your combobox, which is an int, then this example will provide what you need.
public class IntToBoolConverter : IValueConverter
{
// from view model to view
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool)
{
bool trueFalse = (bool)value;
return trueFalse == true ? 0 : 1;
}
return value;
}
// from view to model
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is int)
{
int index = (int)value;
if (index == 0)
return true;
if (index == 1)
return false;
}
return value;
}
}
Amend the SelectedIndex binding to
SelectedItem="{Binding SelectedADM_M022.BtchFlg,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged, Converter={StaticResource boolConverter}}"
given you have a resource called boolConverter that references your converter class e,g,
<Window.Resources>
<local:IntToBoolConverter x:Key="boolConverter" />
</Window.Resources>
Upvotes: 2