gpt4 book ai didi

c# - 如何在 XAML 中访问枚举值

转载 作者:太空狗 更新时间:2023-10-30 01:21:34 25 4
gpt4 key购买 nike

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

我想做的是,

<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

最佳答案

你应该只需要使用 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

关于c# - 如何在 XAML 中访问枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15221165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com