Caliburn.Micro ComboBox 中的枚举绑定
Caliburn.Micro Enum binding in ComboBox
我有一个枚举
public enum FuelType
{
Diesel,
Petrol,
E10
}
如何使用 Caliburn.Micro
将其绑定到组合框
xaml: <ComboBox x:Name="Fuel" Grid.Row="5" Grid.Column="2" Margin="3"/>
和 ModelView 中的 属性:
public FuelType Fuel
{
get { return _fuel; }
set
{
_fuel = value;
NotifyOfPropertyChange(nameof(Fuel));
}
}
执行此操作的正确方法是在 ViewModel 中包含项目列表和所选项目。 Caliburn.Micro 中的约定旨在解析 ItemsSource
(使用 <x:Name>
)和 SelectedItem(使用 Selected<x:Name>
)。
ViewModel:
internal class FuelViewModel : Screen
{
public FuelViewModel()
{
FuelType = Enum.GetValues(typeof(Fueltype)).Cast<Fueltype>().ToList();
}
private Fueltype selectedFuelType;
public Fueltype SelectedFuelType
{
get => selectedFuelType;
set => Set(ref selectedFuelType, value);
}
public IReadOnlyList<Fueltype> FuelType { get; }
}
查看:
<ComboBox x:Name="FuelType"/>
编辑:
不执行 Sybren 的 link 建议的原因是它通过制作视图控制数据破坏了 MVVM 原则。如果您要从一个简单的枚举支持更改为支持您的视图中断的数据库。使用正确的方法,您可以在根本不接触视图的情况下更改 ViewModel 中的类型,并且您还可以在不破坏 ViewModel 的情况下交换视图。
我有一个枚举
public enum FuelType
{
Diesel,
Petrol,
E10
}
如何使用 Caliburn.Micro
将其绑定到组合框xaml: <ComboBox x:Name="Fuel" Grid.Row="5" Grid.Column="2" Margin="3"/>
和 ModelView 中的 属性:
public FuelType Fuel
{
get { return _fuel; }
set
{
_fuel = value;
NotifyOfPropertyChange(nameof(Fuel));
}
}
执行此操作的正确方法是在 ViewModel 中包含项目列表和所选项目。 Caliburn.Micro 中的约定旨在解析 ItemsSource
(使用 <x:Name>
)和 SelectedItem(使用 Selected<x:Name>
)。
ViewModel:
internal class FuelViewModel : Screen
{
public FuelViewModel()
{
FuelType = Enum.GetValues(typeof(Fueltype)).Cast<Fueltype>().ToList();
}
private Fueltype selectedFuelType;
public Fueltype SelectedFuelType
{
get => selectedFuelType;
set => Set(ref selectedFuelType, value);
}
public IReadOnlyList<Fueltype> FuelType { get; }
}
查看:
<ComboBox x:Name="FuelType"/>
编辑:
不执行 Sybren 的 link 建议的原因是它通过制作视图控制数据破坏了 MVVM 原则。如果您要从一个简单的枚举支持更改为支持您的视图中断的数据库。使用正确的方法,您可以在根本不接触视图的情况下更改 ViewModel 中的类型,并且您还可以在不破坏 ViewModel 的情况下交换视图。