user1097108
user1097108

Reputation: 355

WPF data binding to dictionary with enum key

I have a solution with a couple of projects. In one project, is my model that has an enum called ModelEnum.

Then in my WPF project I have a ViewModel which has a Dictionary.

And in my ViewModel I have my ValuesDictionary setup as:

    private Dictionary<ModelEnum, string> _valuesDictionary = new Dictionary<ModelEnum, string>();

    public Dictionary<ModelEnum, string> ValuesDictionary
    {
        get { return _valuesDictionary; }
        set { _valuesDictionary = value; OnPropertyChanged(_valuesDictionary); }
    }

In my XAML I have:

xmlns:model="clr-namespace:Model.Data;assembly=Model"
...
<TextBox Text="{Binding Path=ValuesDictionary[(model:ModelEnum)ModelEnum.Enum1].Value}" HorizontalAlignment="Left" Height="29" Margin="90,82,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="50"/>

The following XAML snippet:

(model:ModelEnum)ModelEnum.Enum1

is giving me the error "Parameter type mismatch." I'm confused because I thought I was casting this to the Enum type that it was expecting. I referenced this SO question to try it with no luck.

Upvotes: 2

Views: 1696

Answers (2)

ack
ack

Reputation: 51

Just to add to the potential pitfalls with this, I had issues binding without the explicit "Path="

i.e.

{Binding ValuesDictionary[(model:ModelEnum)Enum1]}

doesn't work, but:

{Binding Path=ValuesDictionary[(model:ModelEnum)Enum1]}

works as expected, although the designer (or maybe ReSharper) still complains about syntax errors.

Upvotes: 5

Taran
Taran

Reputation: 98

replace

(model:ModelEnum)ModelEnum.Enum1].Value

with

(model:ModelEnum)Enum1]

Then try. I hope it will work.

Upvotes: 8

Related Questions