加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用枚举作为键绑定到Dictionary中的值

发布时间:2020-12-15 08:15:52 所属栏目:百科 来源:网络整理
导读:我是一些应用程序,我想将一些文本框和chekcbox绑定到Dictionary(Enum,string)的值字段.这是可能的,我该怎么做? 在xaml代码中我有这样的东西 – 它用于字典,字符串作为键,但它无法正确绑定到枚举键 dxe:TextEdit EditValue="{Binding Properties[PrimaryAddr
我是一些应用程序,我想将一些文本框和chekcbox绑定到Dictionary(Enum,string)的值字段.这是可能的,我该怎么做?

在xaml代码中我有这样的东西 – 它用于字典,字符串作为键,但它无法正确绑定到枚举键

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

..这就是我在Enum中所拥有的

public enum MyEnum
{
    PrimaryAddress,SecondaryAddress,UsePrimaryAddress
}

在ViewModel字典中定义为:

public Dictionary<MyEnum,string> Properties

我找到了具有枚举值的combobox解决方案,但这不适用于我的情况.

有什么建议?

解决方法

您必须在绑定表达式中为索引器的参数设置适当的类型.

查看型号:

public enum Property
{
    PrimaryAddress,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>

代码隐藏:

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

有关详细信息,请参阅“Binding Path Syntax”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读