C# 社区工具包 Mvvm 源代码生成器:ObservableProperty

C# Community Toolkit Mvvm Source Generator: ObservableProperty

Community.Toolkit.Mvvm 库有助于使用特殊属性为字段生成属性。如何使用此属性来自动执行这样的 属性?如何制作这样的条目?

using CommunityToolkit.Mvvm.ComponentModel;

public partial class InfoViewModel : BaseViewModel
{
    private readonly A.Info _item;

    public ViewModel(A.Info item)
    {
        _item = item;
    }

    public ViewModel()
    {
        _item = new A.DateInfo();
    }
    
    //[ObservableProperty]
    //private string year;
    public string Year
    {
        get => _item.Year;
        set
        {
            _item.Year = value;
            OnPropertyChanged(nameof(Year));
        }
    }
}

确保 ViewModelpartial class。只需用 ObservablePropertyAttribute.

装饰一个私有字段
using CommunityToolkit.Mvvm.ComponentModel;

public partial class ViewModel
{
    [ObservableProperty]
    private string year;
}

编辑

根据您在评论中所写的内容,这里有一些处理方法。

选项 1 - 使项目的年份 属性 可观察

using CommunityToolkit.Mvvm.ComponentModel;

public partial class MyItem
{
    [ObservableProperty]
    private string year; 
}

public class ViewModel
{
    public MyItem Item { get; }

    public ViewModel(MyItem item)
    {
        Item = item;
    }

    public ViewModel()
    {
        Item = new MyItem();
    }

    private void Save()
    {
        //do something with item here
    }
}

像这样在 xaml 中绑定:

<Entry Text="{Binding Item.Year}" />

选项 2 - 在视图模型上额外 属性

using CommunityToolkit.Mvvm.ComponentModel;

public class MyItem
{
    public string Year { get; set; }
}

public partial class ViewModel
{
    private readonly MyItem _item;

    [ObservableProperty]
    private string year;    

    public ViewModel(MyItem item)
    {
        _item = item;
    }

    public ViewModel()
    {
        _item = new MyItem();
    }

    private void Save()
    {
        _item.Year = Year; //synchronize the year values
        //do something with item here
    }
}

像这样在 xaml 中绑定:

<Entry Text="{Binding Year}" />

工具包包含基础 class:ObservableObjectSetProperty 方法。将此 class 用于您的虚拟机。或者 BaseViewModel : ObservableObject

class MyViewModel : ObservableObject
{
   private string _value;
   public string Value { get = _value; set => SetProperty(ref _value, value); }
}