2

I came across a problem with binding to dictonary property using enum as key in xaml file.

I have a ViewModel with property

public Dictionary<EColor, MyDataStatus> StatusByColor {get; set;}

Where EColor is as enum and MyDataStatus is my own class with property Value.

In a view I'm trying to create a binding

<TextBlock Text="{Binding StatusByColor[enum:EColor.eRed].Value}"/>

and I get an binding error

BindingExpression path error: '[]' property not found on 'object' ''Dictionary`2 .....

However if I enter a digit (instead of using enum) like this:

<TextBlock Text="{Binding StatusByColor[0].Value}"/>

It works perfectly fine

I thought it may be a problem with "including" enum in xaml (it is defined in other assembly) but a few lines below i can use it as CommandParameter like this.

Text="{Binding Path=StatusByColor, Mode=OneWay,
               Converter={StaticResource statusByColorToDayElapsedConverter}, 
               ConverterParameter={x:Static enum:EPaintColor.eRed}}"

And in this scenario (with converterParameter) even IntelliSense suggests enum's values.

This is how I "include" enum in xaml:

"xmlns:enum="clr-namespace:CommonTypes.Enums;assembly=CommonTypes""
2
  • Does this answer your question? Using an enum as an array index in C# Commented Jan 15, 2022 at 14:57
  • I'm afraid it doesn't :( Or maybe I don't understand how to make use of the answers. Commented Jan 15, 2022 at 17:06

1 Answer 1

1

Firstly,Give my answer,and I have verified it.

<TextBlock Text="{Binding StatusByColor[eRed].Value}"/>

I tried your code with a sample and get the same result as you mentioned. But when I try this code.

<TextBlock Text="{Binding StatusByColor[0].Value}"/>

I changed the index from 0 to 999.I got an exception "System.Collections.Generic.KeyNotFoundException" So I confirm that there is a type casting from Int to Enum. However,only Int can be converted? How about string? Yes!String also worked. Refer: WPF Binding to items within a dictionary by key?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.