C# 数据绑定

1.用于通知的类
/// <summary>
    /// 属性修改通知基类,用于实现数据绑定功能
    /// </summary>
    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属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值