wpf 以枚举为键绑定到字典中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12690515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
binding to value in Dictionary with enum as a key
提问by user1714232
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?
我是一些应用程序,我想将一些文本框和 chekcboxes 绑定到 Dictionary(Enum, string) 的值字段。这是可能的,我该怎么做?
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
在 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}" />
.. and here is what I have in Enum
.. 这是我在 Enum 中所拥有的
public enum MyEnum
{
PrimaryAddress,
SecondaryAddress,
UsePrimaryAddress
}
In ViewModel dictionary is defined as:
在 ViewModel 字典中定义为:
public Dictionary<MyEnum, string> Properties
I have found solution for combobox with enum values but this does not apply to my case.
我找到了带有枚举值的组合框的解决方案,但这不适用于我的情况。
Any advice?
有什么建议吗?
回答by Dennis
You have to set appropriate type for indexer's parameter in binding expression.
您必须在绑定表达式中为索引器的参数设置适当的类型。
View model:
查看型号:
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:
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-behind:
代码隐藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
For more info, see "Binding Path Syntax".
有关详细信息,请参阅“绑定路径语法”。

