WPF更新绑定字段

很久没用过wpf了,今晚改一个小工具,折腾了半天,记录备忘一下。

在xaml中绑定好上下文字段

设置绑定上下文

var stu = new Student();
this.DataContext = stu;

Student实现INotifyPropertyChanged

 public class Student : INotifyPropertyChanged
    {
        private string _name;

        public string Name
        {
            get => _name;
            set
            {
                _name = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
}

更新

 Task.Run((async () =>
            {
                while (true)
                {
                    await Task.Delay(1000);
                    stu.Name = DateTime.Now.ToString();
                }
            }));

posted on 2022-10-12 23:15  快乐海盗  阅读(46)  评论(0编辑  收藏  举报