简体   繁体   中英

C# Community Toolkit Mvvm Source Generator: ObservableProperty

The Community.Toolkit.Mvvm library helps to generate properties for fields using special attributes. How can this attribute be used to automate such a property? How to make such an entry?

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

Make sure the ViewModel is a partial class . The just decorate a private field with the ObservablePropertyAttribute .

using CommunityToolkit.Mvvm.ComponentModel;

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

EDIT

From what you've wrote in the comments, here are some ways to deal with it.

Option 1 - make the Item's Year property observable

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

Bind in xaml like this:

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

Option 2 - an extra property on the view model

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

Bind in xaml like this:

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

Toolkit contains base class: ObservableObject with SetProperty method. Use this class for your VM. Or BaseViewModel : ObservableObject

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM