模版1:
cs
public abstract class ViewModelBase : INotifyPropertyChanged
{
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// ... 其他代码 ...
}
public class MyViewModel : ViewModelBase
{
private string _myProperty;
public string MyProperty
{
get => _myProperty;
set
{
if (_myProperty == value) return;
_myProperty = value;
OnPropertyChanged(); // 这里不需要指定属性名,因为使用了CallerMemberName特性
}
}
}
模版2:
cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace zl_screenplayer
{
public class MainViewModel : INotifyPropertyChanged
{
private ObservableCollection<DotViewModel> _dots;
private int _currentIndex;
public ObservableCollection<DotViewModel> Dots
{
get { return _dots; }
set { _dots = value; OnPropertyChanged(); }
}
public int CurrentIndex
{
get { return _currentIndex; }
set
{
if (_currentIndex != value)
{
_dots[_currentIndex].IsActive = false;
_currentIndex = value;
_dots[_currentIndex].IsActive = true;
OnPropertyChanged();
}
}
}
public MainViewModel(int Count,int InitIndex)
{
var list = new ObservableCollection<DotViewModel>();
for (int i = 0; i < Count; i++)
{
list.Add(new DotViewModel { IsActive = (i == InitIndex ? true : false) });
}
Dots = list;
_currentIndex = InitIndex;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class DotViewModel : INotifyPropertyChanged
{
private bool _isActive;
public bool IsActive
{
get { return _isActive; }
set { _isActive = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}