iT邦幫忙

0

MVVM裏的ViewModel如何觸發OnPropertyChanged

  • 分享至 

  • xImage

Base class

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    public void SetValue<T>(ref T property, T value, [CallerMemberName] string propertyName = null)
    {
        if (property != null)
        {
            if (property.Equals(value))
            {
                return;
            }
        }
        property = value;
        OnPropertyChanged(propertyName);
    }
    protected void OnPropertyChanged([CallerMemberName]string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

VM

public class ChartViewModel : BaseViewModel
    {
        public SeriesCollection SeriesCollection => ChartData.Instance.SeriesCollection;
        public string[] Labels => ChartData.Instance.Labels;
        public Func<double, string> YFormatter => x => String.Format("{0:C}", x);
        public ChartViewModel() { }       

    }

其中, SeriesCollection 因繼承自 INotifyPropertyChanged, 當 ChartData 裏的資料更新時, 它會觸發OnPropertyChanged.
但 Labels 只是一個 string[], 當 ChartData 裏資料更新, 它並不會自動更新.
目前我在 ChartData 裏新增一個 event, 再讓VM去訂閱, 然後觸發 OnPropertyChanged.
有其它的方法可以改善嗎?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
JamesDoge
iT邦高手 1 級 ‧ 2023-03-04 12:36:53
public class ChartViewModel : BaseViewModel
{
    public SeriesCollection SeriesCollection => ChartData.Instance.SeriesCollection;

    private string[] _labels;
    public string[] Labels
    {
        get { return _labels; }
        set { SetValue(ref _labels, value); }
    }

    public Func<double, string> YFormatter => x => String.Format("{0:C}", x);

    public ChartViewModel()
    {
        // 初始化 Labels
        Labels = ChartData.Instance.Labels;

        // 訂閱 ChartData 資料更新事件,更新 Labels
        ChartData.Instance.DataUpdated += (sender, args) =>
        {
            Labels = ChartData.Instance.Labels;
        };
    }
}

我要發表回答

立即登入回答