Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding to value in Dictionary with enum as a key

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?

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}" />

.. and here is what I have in Enum

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.

Any advice?

like image 267
user1714232 Avatar asked Oct 02 '12 12:10

user1714232


1 Answers

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:

<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".

like image 167
Dennis Avatar answered Nov 11 '22 05:11

Dennis