下面是我拥有的一个类的简化示例:
public class ExampleClassDto
{
public int DriverTypeId
}
我还有一个枚举,将 DriverType 的 ID 映射到有意义的名称:
public enum DriverType
{
None,
Driver1,
Driver2,
Driver3
}
但我想在 XAML 中将其绑定(bind)到组合框。不幸的是,由于类型不匹配,它不喜欢这样。所以在我的 ViewModel 中,我必须创建第二个属性来映射这两个
public class ExampleViewModel
{
private ExampleClassDto _selectedExampleClass;
public ExampleClassDto SelectedExampleClass
{
get { return _selectedExampleClass; }
set
{
_selectedExampleClass = value;
SelectedDriverType = (DriverType)_selectedExampleClass.DriverTypeId;
OnPropertyChanged("SelectedDeviceType");
}
}
public DriverType SelectedDriverType
{
get
{
if (_selectedDeviceType != null)
{
return (DriverType)_selectedDeviceType.DriverTypeId;
}
return DriverType.None;
}
set
{
_selectedDeviceType.DriverTypeId = (int) value;
OnPropertyChanged("SelectedDriverType");
}
}
}
然后我绑定(bind)到新属性。
<ComboBox ItemsSource="{Binding Source={StaticResource DriverTypeEnum}}" SelectedValue="{Binding SelectedDriverType, Mode=TwoWay}"/>
现在,这可行,但感觉非常恶心。它使用 SelectedDriverType 作为转换器。我想避免必须将 DTO 的属性设置为不同的类型。还有其他更优雅的解决方案吗?
谢谢!
最佳答案
您可以使用一个通用转换器 EnumConverter
,它将将 int 转换为 Enum
以在 XAML 上显示它并从 Enum 转换回 int
在您的 ViewModel 类中设置。
它适用于任何枚举类型。您只需要在转换器参数中传递枚举类型。
public class EnumConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
Enum enumValue = default(Enum);
if (parameter is Type)
{
enumValue = (Enum)Enum.Parse((Type)parameter, value.ToString());
}
return enumValue;
}
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
int returnValue = 0;
if (parameter is Type)
{
returnValue = (int)Enum.Parse((Type)parameter, value.ToString());
}
return returnValue;
}
}
XAML 用法:
<ComboBox ItemsSource="{Binding Source={StaticResource DriverTypeEnum}}"
SelectedValue="{Binding DriverTypeId,
Converter={StaticResource EnumConverter},
ConverterParameter={x:Type local:DriverType}}"/>
local
是声明 DriverType 的命名空间。
关于c# - 数据绑定(bind) Int 属性到 WPF 中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707160/