创建ViewBase类,重写INotifyPropertyChanged接口,实现数据更新
public class ViewBase : INotifyPropertyChanged { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public class CallerMemberNameAttribute : Attribute { } public event PropertyChangedEventHandler PropertyChanged; protected void UpdateProper<T>(ref T properValue, T newValue, [CallerMemberName] string properName = "") { if (object.Equals(properValue, newValue)) return; properValue = newValue; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(properName)); } }
与xaml对应的ViewModel,继承ViewBase
public class MainWindowView:ViewBase { private string stuName; public string StuName { get => stuName; set => UpdateProper(ref stuName, value); } }
xaml.cs中
public MainWindow()//构造方法 { InitializeComponent(); view = new MainWindowView(); this.DataContext = view; } MainWindowView view;//相应的ViewModel对象名
xaml中
<TextBox Text="{Binding StuName}"></TextBox>
若实现双向绑定则更改UpdateSourceTrigger属性,该属性是数据更新的触发方式
<TextBox Text="{Binding StuName,UpdateSourceTrigger=PropertyChanged}"></TextBox>