using System;using System.ComponentModel;using System.Runtime.CompilerServices;namespace MvvmDemo.Common{ /// /// Viewmodel基类,属性双向绑定基础 /// public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; /// /// 属性变更通知 /// /// 属性名 public void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }}
第二步:各个ViewModel继承基类。
public class UserViewModel : ViewModelBase { private string _userId; private string _userName; /// /// 用户名 /// public string UserId { get { return _userId; } set { _userId = value; NotifyPropertyChanged(); } } /// /// 用户名 /// public string UserName { get { return _userName; } set { _userName = value; NotifyPropertyChanged(); } } }
第三步:Xaml绑定属性,实现消息通知。
备注:通过IValueConverter可以做一些特殊绑定处理。比如,经典的就是Bool值控制Visibility。
[ValueConversion(typeof(bool), typeof(Visibility))] public class BoolToVisibiltyConvert