本来想这是原创 不过貌似已经有很多资料介绍的很详细
直接搜 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来加 都需要根据具体情况来定