C# 数据绑定

1.用于通知的类
///
    /// 属性修改通知基类,用于实现数据绑定功能
    ///
    public class PropertyChangedBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
2.数据层
public class TestBindingData : PropertyChangedBase
    {
        public static TestBindingData Instance
        {
            get
            {
                if (null == m_Instance)
                    m_Instance = new TestBindingData();
                return m_Instance;
            }
        }

        public string BindingData
        {
            get { return m_TestBindingData; }
            set
            {
                m_TestBindingData = value;
                NotifyPropertyChanged();
            }
        }
        private string m_TestBindingData = string.Empty;
        private static volatile TestBindingData m_Instance = new TestBindingData();
        private static object m_SyncObj = new object();
    }

3.用于绑定的部分代码:
Binding binding = new Binding();
binding.Mode = BindingMode.TwoWay;
binding.NotifyOnTargetUpdated = true;
binding.BindsDirectlyToSource = true;
binding.Path = new PropertyPath("BindingData");
binding.Source = TestBindingData.Instance;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
DependencyProperty dependProperty = TextBox.TextProperty;
BindingOperations.SetBinding(TestBindingTextBox, dependProperty, binding);

注:标红的属性表示,当UI层的文本框数据改变时,马上通知数据层,触发数据层的Set属性。

你可能感兴趣的:(C# 数据绑定)