将布尔值绑定到组合框

时间:2013-11-27 22:52:22

标签: c# wpf data-binding combobox

我有一个Combobox,我想编辑一个布尔值。

        <dxe:ComboBoxEdit ItemsSource="{Binding EnumItemsSource}" 
                          DisplayMember="Name"
                          ValueMember="Id"
                          IsTextEditable="False"
                          EditValue="{Binding TargetValue, UpdateSourceTrigger=PropertyChanged}"/>

我的ViewModel:

    /// <summary>
    /// Contains the ItemsSource for Enums
    /// </summary>
    public List<EnumItemObject> EnumItemsSource
    {
        get { return _enumItemsSource; }
        set
        {
            _enumItemsSource = value;
            OnPropertyChanged();
        }
    }

public class EnumItemObject
{
   public int Id {get;set;}
   public string Name {get;set;}
}

我准备了Combobox ItemsSource的数据:

    /// <summary>
    /// Sets the value to the properties for the BitTemplate view. (similar with EnumTemplate)
    /// </summary>
    /// <param name="propertyInfo">a boolean property</param>
    private void PrepareDataForBitTemplate(PropertyInfo propertyInfo)
    {
        TargetValue = (int)propertyInfo.GetValue(_firstSelectedItem);
        EnumItemsSource = new List<EnumItemObject>();
        EnumItemsSource.Add(new EnumItemObject() { Id = 0, Name = "Nein" });
        EnumItemsSource.Add(new EnumItemObject() { Id = 1, Name = "Ja" });
    }

方法是否正确?任何解决方案都比较容易吗?

由于

1 个答案:

答案 0 :(得分:0)

WPF中更自然的方式是使用 Value Converter 。简而言之,它是一个操纵属性值如何绑定到UI对象的对象。

在你的情况下,这意味着(例如 - 当然有更多的方法)创建一个转换器,它将布尔值转换为01,然后你可以将该属性绑定到{{带有该转换器的预定义文本Nein / Ja值(在正确的索引上)的SelectedIndex的1}}。

<小时/> 一个不相关的事情:如果您使用除英语之外的其他语言的GUI文本开发您的应用程序,我会考虑将其移动到具有键的英文名称的资源文件 - 例如,使不能说德语的人更容易访问代码。可能是你不需要它的情况,我只是觉得我应该提到它:)

相关问题