如何将布尔值绑定到 wpf 中的组合框 [英] how to bind a boolean to combobox in wpf

查看:37
本文介绍了如何将布尔值绑定到 wpf 中的组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我想知道如何将布尔属性绑定到组合框.组合框将是一个是/否组合框.

Well I was wondering how to bind a boolean property to a combobox.Combobox will be a yes/no combobox.

推荐答案

您可以使用 ValueConverter 将布尔值转换为 ComboBox 索引并返回.像这样:

You could use a ValueConverter to convert the boolean value to a ComboBox index and back. Like this:

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;
        }
    }
}

假设 Yes 在索引 0 上,No 在索引 1 上.那么您必须使用该转换器绑定到 SelectedIndex 属性.为此,您在资源部分声明转换器:

Assuming Yes is on index 0 and No on index 1. Then you'd have to use that converter in binding to the SelectedIndex property. For this, you declare your converter in your resources section:

  <Window.Resources>
    <local:BoolToIndexConverter x:Key="boolToIndexConverter" />
  </Window.Resources>

然后在绑定中使用它:

<ComboBox SelectedIndex="{Binding YourBooleanProperty, Converter={StaticResource boolToIndexConverter}}"/>

这篇关于如何将布尔值绑定到 wpf 中的组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆