3

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.

Yegor
  • 2,514
  • 2
  • 19
  • 27

2 Answers2

3

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.

Neutrino
  • 8,496
  • 4
  • 57
  • 83
1

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.

Matt Hamilton
  • 200,371
  • 61
  • 386
  • 320