创建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>

 

相关文章:

  • 2022-12-23
  • 2022-02-28
  • 2021-09-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
猜你喜欢
  • 2021-06-20
  • 2021-06-13
  • 2022-12-23
  • 2021-05-23
  • 2021-10-29
  • 2022-12-23
  • 2021-10-04
相关资源
相似解决方案