2013-03-05 98 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