簡體   English   中英

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

確保ViewModel是一個partial class 只需使用ObservablePropertyAttribute裝飾一個私有字段。

using CommunityToolkit.Mvvm.ComponentModel;

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

編輯

根據您在評論中所寫的內容,這里有一些處理方法。

選項 1 - 使 Item's Year 屬性可觀察

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}" />

Toolkit 包含基類:帶有SetProperty方法的ObservableObject 將此類用於您的 VM。 BaseViewModel : ObservableObject

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM