如何在WPF中将布尔值绑定到ComboBox?

15

我想知道如何将布尔属性绑定到组合框中。组合框将是一个是/否组合框。

5个回答

24

您可以使用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}}"/>

很棒的答案。这个链接提供了更多关于这个主题的信息。 - estebro

15

过去我发现自己经常使用ComboBox项目的IsSelected属性。 这种方法完全在xaml中实现。

<ComboBox>
    <ComboBoxItem Content="No" />
    <ComboBoxItem Content="Yes" IsSelected="{Binding YourBooleanProperty, Mode=OneWayToSource}" />
</ComboBox>

1
这个代码完美运行,但是第一次 ComboBox 没有任何值被选中。你可以通过添加 SelectedIndex 强制设置默认值,例如 <ComboBox SelectedIndex="0"> - chviLadislav
1
你可以在“否”框上放一个转换器,以反转IsSelected布尔绑定,然后它应该只需使用来自你的视图模型的默认值。 - Denise Skidmore

11

第一种解决方案是用复选框替换你的“是/否”组合框,因为毕竟复选框是有原因存在的。

第二种解决方案是用true和false对象填充你的组合框,然后将组合框的“SelectedItem”与你的布尔属性绑定。


笑,不确定我是否采用你的解决方案,但+1,因为这甚至没有在我脑海中出现。 - Jeff

3

以下是一个例子(用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);
    }
}

无需操作索引。


0
你可以利用 ComboBoxItem.Tag 属性来实现这个功能:
<ComboBox SelectedValue="{Binding BooleanProperty}" SelectedValuePath="Tag">
   <ComboBoxItem Tag="False">No</ComboBoxItem>
   <ComboBoxItem Tag="True">Yes</ComboBoxItem>
</ComboBox>

在 .NET 6 中运行良好(可能也适用于旧版本)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接