如何将布尔值绑定到wpf中的组合框
答
您可以使用ValueConverter将布尔值转换为ComboBox索引并返回。像这样:
public class BoolToIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value == true) ? 0 : 1;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((int)value == 0) ? true : false;
}
}
}
假设是在索引0和否在索引1.然后,你必须使用该转换器绑定到SelectedIndex属性。对于这一点,你宣布你的转换器在你的资源部分:
<Window.Resources>
<local:BoolToIndexConverter x:Key="boolToIndexConverter" />
</Window.Resources>
然后你用它在你的绑定:
<ComboBox SelectedIndex="{Binding YourBooleanProperty, Converter={StaticResource boolToIndexConverter}}"/>
答
首先解决方案是一个复选框,因为更换你的“是/否”组合框,好吧,复选框存在的原因。
第二种解决方案是使用true和false对象填充组合框,然后将ComboBox的“SelectedItem”绑定到布尔属性。
答
我发现自己在过去使用ComboBox项目的IsSelected属性。这个方法完全在xaml中。
<ComboBox>
<ComboBoxItem Content="No" />
<ComboBoxItem Content="Yes" IsSelected="{Binding YourBooleanProperty, Mode=OneWayToSource}" />
</ComboBox>
答
下面是一个例子(替换启用/是/否禁用):
<ComboBox SelectedValue="{Binding IsEnabled}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={x:Static converters:EnabledDisabledToBooleanConverter.Instance}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.Items>
<system:Boolean>True</system:Boolean>
<system:Boolean>False</system:Boolean>
</ComboBox.Items>
</ComboBox>
这里是转换器:
public class EnabledDisabledToBooleanConverter : IValueConverter
{
private const string EnabledText = "Enabled";
private const string DisabledText = "Disabled";
public static readonly EnabledDisabledToBooleanConverter Instance = new EnabledDisabledToBooleanConverter();
private EnabledDisabledToBooleanConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Equals(true, value)
? EnabledText
: DisabledText;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//Actually won't be used, but in case you need that
return Equals(value, EnabledText);
}
}
而且不需要用指数来打。
啊这很酷感谢队友我是一个新的wpf – user434547 2010-12-02 13:27:54
如果它适合你,你可以标记为答案。 :) – Botz3000 2010-12-02 13:54:26