Binding to dictionary using enum as key
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""
Solution 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?