4

我有一个自定义字典,其中键作为枚举,值作为自定义对象。我需要在 xaml 中绑定这个对象。那我该怎么做呢?

我想做的是,

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

我尝试过的,

<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>

但以上任何一项都不适用于我。下面的代码正在显示枚举值,

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

枚举文件,

public enum MyEnum
{
    Home,
    Report
}

我的字典,

IDictionary<MyEnum, Button> ButtonGroups
4

1 回答 1

4

你应该只需要使用Enum值,但Button没有Text属性,所以我使用了Content

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

测试示例:

xml:

<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>

代码:

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));
        }
    }
}

结果:

在此处输入图像描述

于 2013-03-05T10:22:24.767 回答