WPF 自定义模版 Style 中控件引用方法

本文介绍了一种在WPF中优化控件绑定和事件处理的方法,通过使用字典存储控件绑定和事件处理逻辑,减少重复代码,提高编程效率。详细解释了如何在OnApplyTemplate方法中实现这一优化。

本来想这是原创 不过貌似已经有很多资料介绍的很详细

直接搜 WPF+ OnApplyTemplate

这里直接贴我找到的一个链接

https://www.cnblogs.com/wywnet/p/4000372.html

当然也有我自己的一个创新内容

绑定如果想绑定一两个控件  直接后台代码像上面这样写没问题的,

但是如果控件很多,需要绑定,和操作事件很复杂,虽然逃不了必写的代码,但是可以做一些编程的便利写法

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();



            ////从模板中获取名称为PART_IsCheckedCheckBox的CheckBox
            //CheckBox _IsCheckedCheckBox = GetTemplateChild("PART_IsCheckedCheckBox") as CheckBox;
            //if (_IsCheckedCheckBox != null)
            //{
            //    _IsCheckedCheckBox.Click += (sender, e) => Checkbox_Click?.Invoke(this);
            //    //对自己添加的控件进行操作
            //    // 准备Binding
            //    Binding binding = new Binding() { Source = this, Path = new PropertyPath("IsChecked"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
            //    // 连接数据源与绑定目标
            //    BindingOperations.SetBinding(_IsCheckedCheckBox, CheckBox.IsCheckedProperty, binding);
            //}


            Dictionary<string, Action<UIElement>> ControlsBinding = new Dictionary<string, Action<UIElement>>();
            ControlsBinding.Add("PART_IsCheckedCheckBox", x =>
            {
                (x as CheckBox).Click += (sender, e) => Checkbox_Click?.Invoke(this);//传递点击事件触发
                SetControlBinding(x, CheckBox.IsCheckedProperty, "IsChecked");//设置绑定
            });

            foreach (var item in ControlsBinding)
            {
                var tempControl = GetTemplateChild(item.Key) as UIElement;
                if (tempControl != null)
                {
                    item.Value(tempControl);
                }
            }
        }

        protected void SetControlBinding(UIElement Control, DependencyProperty Control_DependencyProperty, string BindingPropertyPath)
        {
            // 准备Binding
            Binding binding = new Binding() { Source = this, Path = new PropertyPath(BindingPropertyPath), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged };
            // 连接数据源与绑定目标
            BindingOperations.SetBinding(Control, Control_DependencyProperty, binding);
        }

        /// <summary>
        /// 点击CheckBox时触发
        /// </summary>
        public event Action<object> Checkbox_Click;

区别是啥呢,当然就是看起来没有那么多的Binding =Bingding辣

 

就这样吧,反正以后写的时候 根据情况判断需要直接 写binding的代码还是foreach来加 都需要根据具体情况来定

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值