在我的程序(MVVM WPF)中有很多枚举,我将枚举绑定到视图中的控件。
有很多方法可以做到这一点。
1) 绑定到 ComboBoxEdit(Devexpress Control)。我正在使用 ObjectDataProvider。
然后这个
<dxe:ComboBoxEdit ItemsSource="{Binding Source={StaticResource SomeEnumValues}>
这工作正常,但在 TabControl 标头中则不然。
2)所以,我想使用IValueConverter,但也没有用。
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
if (!(value is Model.MyEnum))
{
return null;
}
Model.MyEnum me = (Model.MyEnum)value;
return me.GetHashCode();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return null;
}
在 XAML 上:
<local:DataConverter x:Key="myConverter"/>
<TabControl SelectedIndex="{Binding Path=SelectedFeeType,
Converter={StaticResource myConverter}}"/>
3)第三种方法是制作行为依赖属性
像这样的东西
public class ComboBoxEnumerationExtension : ComboBox
{
public static readonly DependencyProperty SelectedEnumerationProperty =
DependencyProperty.Register("SelectedEnumeration", typeof(object),
typeof(ComboBoxEnumerationExtension));
public object SelectedEnumeration
{
get { return (object)GetValue(SelectedEnumerationProperty); }
set { SetValue(SelectedEnumerationProperty, value); }
}
我想知道处理枚举和绑定枚举的最佳方法是什么。现在我无法将选项卡标题绑定到枚举。
这里有一个更好的方法:
在您的模型上,将此属性:
public IEnumerable<string> EnumCol { get; set; }
(随意将名称更改为适合您的名称,但请记住在任何地方更改它)
在构造函数中具有以下功能(甚至更好,将其放在初始化方法中):
var enum_names = Enum.GetNames(typeof(YourEnumTypeHere));
EnumCol = enum_names ;
这将从YourEnumTypeHere
中获取所有名称,并将它们放在将在 xaml 中绑定到的属性上,如下所示:
<ListBox ItemsSource="{Binding EnumCol}"></ListBox>
现在,显然,它不必是 ListBox,但现在你只是绑定到一个字符串集合,你的问题应该得到解决。