在字典与枚举绑定值作为密钥 [英] binding to value in Dictionary with enum as a key

查看:118
本文介绍了在字典与枚举绑定值作为密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一些应用程序,我想一些文本框和chekcboxes绑定到词典(枚举,字符串)值字段。这是可能的,我该怎么办呢?

I'm some application and i would like to bind some textboxes and chekcboxes to value field of Dictionary(Enum, string). Is this possible and how can I do that?

在XAML code我有这样的事情 - 这是工作辞典字符串作为关键,但它不能正确地绑定到与枚举键

In xaml code I have something like this - it is working for Dictionary with string as a key, but it cannot correctly bind to key with enum

<dxe:TextEdit EditValue="{Binding Properties[PrimaryAddress],  Mode=TwoWay}" />
<dxe:TextEdit EditValue="{Binding Properties[SecondaryAddress],  Mode=TwoWay}" />
<dxe:CheckEdit EditValue="{Binding Properties[UsePrimaryAddress], Mode=TwoWay}" />

..这里是我的枚举

public enum MyEnum
{
    PrimaryAddress,
    SecondaryAddress,
    UsePrimaryAddress
}

在视图模型字典的定义是:

In ViewModel dictionary is defined as:

public Dictionary<MyEnum, string> Properties

我已经找到解决方案与枚举值的组合框,但这并不适用于我的情况。

I have found solution for combobox with enum values but this does not apply to my case.

任何意见?

推荐答案

您必须设置索引器的参数适当类型的结合前pression。

You have to set appropriate type for indexer's parameter in binding expression.

查看模式:

public enum Property
{
    PrimaryAddress,
    SecondaryAddress,
    UsePrimaryAddress
}

public class ViewModel
{
    public ViewModel()
    {
        Properties = new Dictionary<Property, object>
        {
            { Property.PrimaryAddress, "123" },
            { Property.SecondaryAddress, "456" },
            { Property.UsePrimaryAddress, true }
        };
    }

    public Dictionary<Property, object> Properties { get; private set; }
}

XAML:

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication5"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <TextBox Grid.Row="0" Text="{Binding Path=Properties[(local:Property)PrimaryAddress]}"/>
        <TextBox Grid.Row="1" Text="{Binding Path=Properties[(local:Property)SecondaryAddress]}"/>
        <CheckBox Grid.Row="2" IsChecked="{Binding Path=Properties[(local:Property)UsePrimaryAddress]}"/>
    </Grid>
</Window>

code-背后:

Code-behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

有关更多信息,请参阅绑定路径语法

For more info, see "Binding Path Syntax".

这篇关于在字典与枚举绑定值作为密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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