Indexing collection properties with enums in XAML

While it {Binding Path=CollectionProperty[2]}

works fine, I cannot get it to work with an enum, i.e. {Binding Path=CollectionProperty[SomeEnum.Value2]}

... What would be the correct syntax for this, if possible at all? Thank.

+3


source to share


2 answers


Just specify the enum value as a string with no picture. For example. Given:

public enum Foo
{
    Value1,
    Value2
}

public class MainWindowVm
{
    public string this[Foo foo]
    {
        get { return Enum.GetName(typeof(Foo), foo); }
    }
}

      

Specify the enumeration value as follows:



<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 maps the supplied string to the values ​​supported by the target enum.

+2


source


Well, I tried binding to a type property Dictionary<Foo, String>

(where Foo

is an enum) like:

{Binding Foos[{x:Static my:Foo.Fizz}]}

      

... but this resulted in a binding exception at runtime.

Curiously, however, using an int index as an indexer even for properties indexed on an enum seems to work. It:



{Binding Foos[2]}

      

... worked great. So if you want to represent your enum values ​​as integers in XAML, you can do it this way.

Otherwise, I think it would be best to bind directly to Foos

via a value converter, passing {x:Static my:Foo.Bar}

as the converter parameter.

+1


source







All Articles