我有一个自定义词典,其中键作为枚举,值为自定义对象。我需要在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
答案 0 :(得分:4)
您只需使用Enum
值,但Button
没有Text
属性,因此我使用Content
<Button Content="{Binding ButtonGroups[Home].Content}">
测试示例:
的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>
代码:
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));
}
}
}
结果: