我想知道如何将布尔属性绑定到组合框中。组合框将是一个是/否组合框。
您可以使用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}}"/>
过去我发现自己经常使用ComboBox项目的IsSelected属性。 这种方法完全在xaml中实现。
<ComboBox>
<ComboBoxItem Content="No" />
<ComboBoxItem Content="Yes" IsSelected="{Binding YourBooleanProperty, Mode=OneWayToSource}" />
</ComboBox>
SelectedIndex
强制设置默认值,例如 <ComboBox SelectedIndex="0">
。 - chviLadislav第一种解决方案是用复选框替换你的“是/否”组合框,因为毕竟复选框是有原因存在的。
第二种解决方案是用true和false对象填充你的组合框,然后将组合框的“SelectedItem”与你的布尔属性绑定。
以下是一个例子(用yes/no替代enabled/disabled):
<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);
}
}
无需操作索引。
<ComboBox SelectedValue="{Binding BooleanProperty}" SelectedValuePath="Tag">
<ComboBoxItem Tag="False">No</ComboBoxItem>
<ComboBoxItem Tag="True">Yes</ComboBoxItem>
</ComboBox>
在 .NET 6 中运行良好(可能也适用于旧版本)。