本來想這是原創 不過貌似已經有很多資料介紹的很詳細
直接搜 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來加 都需要根據具體情況來定