[英]binding to value in Dictionary with enum as a key
我是一些應用程序,我想將一些文本框和 chekcboxes 綁定到 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
我找到了帶有枚舉值的組合框的解決方案,但這不適用於我的情況。
有什么建議嗎?
您必須在綁定表達式中為索引器的參數設置適當的類型。
查看型號:
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>
代碼隱藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
有關詳細信息,請參閱“ 綁定路徑語法”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.