While {Binding Path=CollectionProperty[2]}
works fine, I can't get it working with an enum, i.e. {Binding Path=CollectionProperty[SomeEnum.Value2]}
. What would be a proper syntax for that, if possible at all? Thanks.
2 Answers
Just specify the enum value as an unadorned string. E.g. given:
public enum Foo
{
Value1,
Value2
}
public class MainWindowVm
{
public string this[Foo foo]
{
get { return Enum.GetName(typeof(Foo), foo); }
}
}
Specify the enum value like so:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowVm/>
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding Path=[Value1]}"/>
</Grid>
</Window>
x:Static markup extension is not required because the XAML parser has built in support that will map the provided string to the values supported by the target enum.

- 8,496
- 4
- 57
- 83
-
Working perfectly. Thanks. – MoonStom Feb 20 '16 at 06:23
Well, I tried binding to a property of type Dictionary<Foo, String>
(where Foo
is an enum) like this:
{Binding Foos[{x:Static my:Foo.Fizz}]}
... but that threw a binding exception at runtime.
Curiously, though, using an int as the indexer even for properties that are indexed on an enum seems to work. This:
{Binding Foos[2]}
... worked just fine. So if you're willing to represent your enum values as integers in XAML then you can do it that way.
Otherwise I think your best bet would be to bind directly to Foos
through a value converter, passing {x:Static my:Foo.Bar}
as the converter parameter.

- 200,371
- 61
- 386
- 320
-
Yes, that's what I'm talking about. Using conversion is a fallback option. Thank you. – Yegor Apr 06 '12 at 10:12