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.
有其它的方法可以改善嗎?
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;
};
}
}