昨天本人写了一篇文章《WPF的数据绑定——MVVM模式下控件与类成员及类对象成员双向绑定》,地址为:http://blog.csdn.net/mandylover/article/details/69944513,经进一步调试,发现了一个bug,即改变类对象成员的值后无法更新控件的值。
验证代码是:
public partial class Page1 : Page
{
private TestViewMode vm = null;
public Page1()
{
InitializeComponent();
vm = TestViewMode.CreateInstance();
this.DataContext = vm;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
vm.tc.strName = "重新命名,但是没想好名字";
}
}
经分析,如果赋值给类对象(vm.tc),会触发通知,但赋值给类对象的成员变量(vm.tc.strName),则不会。
那我们必须对ViewMode进行调整,需在调用类的成员也设置绑定属性改变通知,才能实现类对象成员双向绑定的功能,修正的代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
namespace TestBinding
{
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, String propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged(string propertyName = null)
{
PropertyChangedEventHandler eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
class TestViewMode : BindableBase
{
//public event PropertyChangedEventHandler PropertyChanged;
//protected void OnPropertyChanged(string propertyName)
//{
// PropertyChangedEventHandler handler = PropertyChanged;
// if (handler != null)
// {
// handler(this, new PropertyChangedEventArgs(propertyName));
// }
//}
//建立静态对象,以便复用
public static TestViewMode vm = null;
private TestViewMode()
{
strTempText = "这是ViewMode的一个成员变量";
tc = new TempClass();
tc.strName = "来自其他类的成员变量";
}
/// <summary>
/// 创建ViewModel实例,先判断一下是否已存在,如已存在,则使用之前实例对象
/// </summary>
/// <returns>返回实例对象</returns>
public static TestViewMode CreateInstance()
{
if (vm == null)
{
vm = new TestViewMode();
}
return vm;
}
/// <summary>
/// 类内成员
/// </summary>
private string _strTempText = "";
public string strTempText
{
get { return _strTempText; }
set
{
_strTempText = value;
OnPropertyChanged("strTempText");
}
}
/// <summary>
/// 类对象
/// </summary>
private TempClass _tc = null;
public TempClass tc
{
get
{
return _tc;
}
set
{
_tc = value;
OnPropertyChanged("tc");
}
}
}
public class TempClass:BindableBase
{
//public string strName { get; set; }
private string _strName = "";
public string strName
{
get
{
return _strName;
}
set
{
SetProperty(ref _strName, value, "strName");
}
}
}
}
重新运行,可实现双向绑定,如下:
更新后的代码:http://download.csdn.net/detail/mandylover/9810572