【问题标题】:Caliburn.Micro Enum binding in ComboBoxComboBox 中的 Caliburn.Micro 枚举绑定
【发布时间】:2017-11-24 22:28:00
【问题描述】:

我有一个枚举

    public enum FuelType
{
    Diesel,
    Petrol,
    E10
}

如何使用 Caliburn.Micro 将其绑定到 Combobox

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));
        }
    }

【问题讨论】:

标签: c# wpf enums combobox caliburn.micro


【解决方案1】:

执行此操作的正确方法是在 ViewModel 中有一个项目列表和选定项目。 Caliburn.Micro 中的约定设置为解析ItemsSource(使用<x:Name>)和SelectedItem(使用Selected<x:Name>)。

视图模型:

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 的链接建议的原因是它通过制作视图控制数据来破坏 MVVM 原则。如果您要从简单的枚举支持更改为支持您的视图中断的数据库。使用正确的方法,您可以在不接触视图的情况下更改 ViewModel 中的类型,还可以在不破坏 ViewModel 的情况下交换视图。

【讨论】:

    猜你喜欢
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多