wpf 如何在 XAML 中访问枚举值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15221165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Access enum value in XAML
提问by Chamika Sandamal
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?
我有一个自定义字典,键作为枚举,值作为自定义对象。我需要在 xaml 中绑定这个对象。那我该怎么做呢?
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
采纳答案by sa_ddam213
You should only have to use the Enumvalue, But Buttondoes not have a Textproperty, so I used Content
你应该只需要使用Enum值,但Button没有Text属性,所以我用Content
<Button Content="{Binding ButtonGroups[Home].Content}">
Test Example:
测试示例:
Xaml:
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>
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:
结果:



