WPF双向绑定

数据绑定模式共有四种:OneTime、OneWay、OneWayToSource和TwoWay,默认是TwoWay。

TwoWay 当发生更改时的目标属性或源属性更新目标属性。
OneWay 仅当源属性更改时,请更新目标属性。
OneTime 仅当应用程序启动时或时,请更新目标属性DataContext发生了更改。
OneWayToSource 目标属性更改时,请更新源属性。

  1. 实现INotifyPropertyChanged并通过OnPropertyChanged主动更新绑定的控件
 public class BindEx : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;


        protected internal virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
  1. 构造model
 public class testModel : BindEx
    {
        private string _test="";
        public string test
        {
            get
            {
                return _test;
            }
            set
            {
                _test = value;
                OnPropertyChanged("test");
            }
        }
    }
  1. 绑定数据
        <TextBox Text="{Binding test}"/>
 model = new testModel
            {
                test = "test"
            };
            this.DataContext = model;
原文地址:https://www.cnblogs.com/ives/p/wpf_bind.html