zoukankan      html  css  js  c++  java
  • WPF MVVM实现INotifyPropertyChanged数据监听

    创建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>
  • 相关阅读:
    辅助工具链接
    参考资料链接
    oracle sql 查询前十条数据
    oracle sql 按照汉字规则排序
    oracle sql 修改timestamp数据
    eclipse闪退
    js 数组Array
    面试题:树的子结构
    面试题:二叉树中和为某一路径
    面试题:二叉搜索树的后序遍历
  • 原文地址:https://www.cnblogs.com/Stay627/p/13965451.html
Copyright © 2011-2022 走看看