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

前端之家收集整理的这篇文章主要介绍了c# – 使用枚举作为键绑定到Dictionary中的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是一些应用程序,我想将一些文本框和chekcBox绑定到Dictionary(Enum,string)的值字段.这是可能的,我该怎么做?

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

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

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

  1. public enum MyEnum
  2. {
  3. PrimaryAddress,SecondaryAddress,UsePrimaryAddress
  4. }

viewmodel字典中定义为:

  1. public Dictionary<MyEnum,string> Properties

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

有什么建议?

解决方法

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

查看型号:

  1. public enum Property
  2. {
  3. PrimaryAddress,UsePrimaryAddress
  4. }
  5.  
  6. public class viewmodel
  7. {
  8. public viewmodel()
  9. {
  10. Properties = new Dictionary<Property,object>
  11. {
  12. { Property.PrimaryAddress,"123" },{ Property.SecondaryAddress,"456" },{ Property.UsePrimaryAddress,true }
  13. };
  14. }
  15.  
  16. public Dictionary<Property,object> Properties { get; private set; }
  17. }

XAML:

  1. <Window x:Class="WpfApplication5.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. xmlns:local="clr-namespace:WpfApplication5"
  5. Title="MainWindow" Height="350" Width="525">
  6. <Grid>
  7. <Grid.RowDefinitions>
  8. <RowDefinition/>
  9. <RowDefinition/>
  10. <RowDefinition/>
  11. </Grid.RowDefinitions>
  12.  
  13. <TextBox Grid.Row="0" Text="{Binding Path=Properties[(local:Property)PrimaryAddress]}"/>
  14. <TextBox Grid.Row="1" Text="{Binding Path=Properties[(local:Property)SecondaryAddress]}"/>
  15. <CheckBox Grid.Row="2" IsChecked="{Binding Path=Properties[(local:Property)UsePrimaryAddress]}"/>
  16. </Grid>
  17. </Window>

代码隐藏:

  1. public partial class MainWindow : Window
  2. {
  3. public MainWindow()
  4. {
  5. InitializeComponent();
  6. DataContext = new viewmodel();
  7. }
  8. }

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

猜你在找的C#相关文章