接触WPF已经有两年,大大小小开发过几个项目,但从来没有系统的去学习过。几次开发项目时都觉得十分的恼火,太多的事件稍微考虑不到位就会带来麻烦,为此特地系统的看了一本《C#高级编程》第10版,了解到MVVM框架,看了之后十分欢喜,本篇记录研究MVVM过程。
0001 INotifyPropertyChanged接口的使用
InotifyPropertyChanged接口的作用是通知UI后台数据已经改变,UI相应的做出改变,并没有告诉具体是哪个的控件,而是先广播一样喊出xxx值改变了,谁绑定了它记得自己做改变,非常适用MVVM模式。普通的绑定后台自己修改数据是不会显示在UI上的,所以要适用该接口。
public class ObservableObject : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
/// <summary>
/// Raised when a property on this object has a new value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this object’s PropertyChanged event.
/// </summary>
/// <param name=”propertyName”>The property that has a new value.</param>
public void OnPropertyChanged(string propertyName)
{
this.VerifyPropertyName(propertyName);
if (this.PropertyChanged != null)
{
var e = new PropertyChangedEventArgs(propertyName);
this.PropertyChanged(this, e);
}
}
#endregion // INotifyPropertyChanged Members
#region Debugging Aides
/// <summary>
/// Warns the developer if this object does not have
/// a public property with the specified name. This
/// method does not exist in a Release build.
/// </summary>
[Conditional(“DEBUG”)]
[DebuggerStepThrough]
public void VerifyPropertyName(string propertyName)
{
// Verify that the property name matches a real,
// public, instance property on this object.
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
{
string msg = “Invalid property name: “ + propertyName;
if (this.ThrowOnInvalidPropertyName)
throw new Exception(msg);
else
Debug.Fail(msg);
}
}
/// <summary>
/// Returns whether an exception is thrown, or if a Debug.Fail() is used
/// when an invalid property name is passed to the VerifyPropertyName method.
/// The default value is false, but subclasses used by unit tests might
/// override this property’s getter to return true.
/// </summary>
protected bool ThrowOnInvalidPropertyName { get; private set; }
#endregion // Debugging Aides
}
0010 MVVM数据绑定
在前台建立一个Slider一个TextBox:
<Slider x:Name=“slider” Value=“{Binding MyValue,Mode=TwoWay}” TickFrequency=“1” HorizontalAlignment=“Left” Maximum=“100” Minimum=“0” SmallChange=“1” LargeChange=“10” Margin=“10,187,0,0” VerticalAlignment=“Top” Height=“29” Width=“229”/>
<TextBox x:Name=“textBox” Text=“{Binding MyValue,Mode=TwoWay}” HorizontalAlignment=“Left” Height=“23” Margin=“20,159,0,0” TextWrapping=“Wrap” VerticalAlignment=“Top” Width=“120”/>
绑定的后台数据:
private int _value = 50;
public int MyValue
{
get { return _value; }
set
{
_value = value;
OnPropertyChanged(“MyValue”);
}
}