如何绑定一个布尔值在WPF中的ComboBox [英] how to bind a boolean to combobox in wpf

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

问题描述

好吧,我不知道如何将一个布尔值属性为combobox.Combobox绑定将是一个是/否组合框。

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

假设是位于索引0和无索引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>

然后你用它在你的绑定:

Then you use it in your binding:

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

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

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