【发布时间】:2014-01-09 12:35:24
【问题描述】:
下面是我拥有的一个类的简化示例:
public class ExampleClassDto
{
public int DriverTypeId
}
我还有一个 Enum,它将 DriverType 的 Id 映射到有意义的名称:
public enum DriverType
{
None,
Driver1,
Driver2,
Driver3
}
但我想在 XAML 中将它绑定到组合框。不幸的是,由于类型不匹配,它不喜欢这样。所以在我的 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");
}
}
}
然后我绑定到新属性。
<ComboBox ItemsSource="{Binding Source={StaticResource DriverTypeEnum}}" SelectedValue="{Binding SelectedDriverType, Mode=TwoWay}"/>
现在,这可行,但感觉很恶心。它使用 SelectedDriverType 作为转换器。我想避免使 DTO 的属性成为不同的类型。还有其他更优雅的解决方案吗?
谢谢!
【问题讨论】:
-
DriverTypeId 不能是 DriverType 类型吗?
-
可以,但是 Dto 来自一个单独的库,我现在无法更改 =\
-
那么为什么不扩展现有的类 (
public partial class) 并创建一个类型为DriverType的属性来获取/设置DriverTypeId呢? -
@gleng:我认为,在这种情况下,我宁愿只保留转换器属性。我想知道是否还有其他方法可以在 XAML 中使用 SelectedValue 或 SelectedItem,或者 ValueConverter 是否可以发挥作用
-
我记得我做了一个通用的
IntToEnum转换器,我会大量使用它。ConverterParameter通常设置为{x:Type local:MyEnum}以将枚举类型传递给它,它会将绑定的 int 转换为该枚举值/从该枚举值转换。可能值得花点时间为您的公共图书馆制作一个。
标签: c# wpf xaml data-binding