Chamika Sandamal
Chamika Sandamal

Reputation: 24302

How to Access enum value in XAML

I have a custom dictionary with key as an enum and values as custom object. i need to bind this object in the xaml. so how i can do it?

what i want to do is,

<Button Content="{Binding ButtonGroups[my enum value].Text}"></Button>

what i have tried,

<Button Content="{Binding ButtonGroups[local:MyEnum.Report].Text}"></Button>

<Button Content="{Binding ButtonGroups[x:Static local:MyEnum.Report].Text}">
</Button>

<Button Content="{Binding ButtonGroups[{x:Static local:MyEnum.Report}].Text}">
</Button>

But any of the above is not worked for me.and following code is displaying the enum value,

<Button Content="{x:Static local:MyEnum.Report}"></Button>

Enum file,

public enum MyEnum
{
    Home,
    Report
}

my dictionary,

IDictionary<MyEnum, Button> ButtonGroups

Upvotes: 4

Views: 6503

Answers (1)

sa_ddam213
sa_ddam213

Reputation: 43596

You should only have to use the Enum value, But Button does not have a Text property, so I used Content

 <Button Content="{Binding ButtonGroups[Home].Content}">

Test Example:

Xaml:

<Window x:Class="WpfApplication13.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" x:Name="UI" Width="294" Height="79" >

    <Grid DataContext="{Binding ElementName=UI}">
         <Button Content="{Binding ButtonGroups[Home].Content}" />
    </Grid>
</Window>

Code:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();

        ButtonGroups.Add(MyEnum.Home, new Button { Content = "Hello" });
        NotifyPropertyChanged("ButtonGroups");
    }

    private Dictionary<MyEnum, Button> _buttonGroups = new Dictionary<MyEnum, Button>();
    public Dictionary<MyEnum, Button> ButtonGroups
    {
        get { return _buttonGroups; }
        set { _buttonGroups = value; }
    }

    public enum MyEnum
    {
        Home,
        Report
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }
}

Result:

enter image description here

Upvotes: 4

Related Questions