WPF MVVM實現INotifyPropertyChanged資料監聽
阿新 • • 發佈:2020-11-12
建立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>