Visual Studio creates a BindableBase class in the Common folder of your projects. (Don’t confuse this class with the BindingBase class from which Binding derives.)
BindableBase 是像下面这样定义的
public abstract class BindableBase : INotifyPropertyChanged
{ public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{ if (object.Equals(storage, value))return false; storage = value; this.OnPropertyChanged(propertyName); return true; }
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{ var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{ eventHandler(this, new PropertyChangedEventArgs(propertyName)); } } }
BindableBase 类的使用方法:
using Windows.UI; using ColorScrollWithDataContext.Common; namespace ColorScrollWithDataContext { public class RgbViewModel : BindableBase { double red, green, blue; Color color = Color.FromArgb(255, 0, 0, 0); public double Red{ set { if (SetProperty(ref red, value)) Calculate(); } get { return red; } } public double Green { set { if (SetProperty (ref green, value)) Calculate(); } get { return green; } } public double Blue { set { if (SetProperty (ref blue, value)) Calculate(); } get { return blue; } } public Color Color { set { if (SetProperty (ref color, value)) { this.Red = value.R; this.Green = value.G; this.Blue = value.B; } } get { return color; } } void Calculate() { this.Color = Color.FromArgb(255, (byte)this.Red, (byte)this.Green, (byte)this.Blue); } } }
使用方法 ,定义字段 double red,在 Red里面 属性set 调用
SetProperty(refred, value),就可以了
SetProperty(ref red, value)返回true 表示red 改变,返回false 没有改变 。NET 4.5 。C# 5.0 这样用