2013-03-05 64 views
4

我有一个自定义字典与密钥作为枚举和值作为自定义对象。我需要在xaml中绑定这个对象。所以我该怎么做呢?如何访问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> 

但上述任何下面的代码显示枚举值不工作了me.and,

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

枚举文件,

public enum MyEnum 
{ 
    Home, 
    Report 
} 

我的字典里,

IDictionary<MyEnum, Button> ButtonGroups 

回答

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

结果:

enter image description here

+0

我得到了它的工作'<按钮内容=“{绑定路径= ButtonGroups [(本地:MyEnum)首页]。文本}“/>',但看起来这更容易:)而”文本“不是按钮的属性。该集合包含自定义对象,并且该自定义对象具有名为“文本”的属性。感谢您的快速回复和工作答案 – 2013-03-05 10:29:09

+0

没问题:)快乐编码 – 2013-03-05 10:30:34