wpf通过VisualTreeHelper找到控件内所有CheckBox和TextBox并做相应绑定
#region CheckBox与TextBox绑定
Dictionary<CheckBox, TextBox> CheckTextBoxDic = new Dictionary<CheckBox, TextBox>();
//找到控件下所有勾选框并与其相对应的文本框绑定
private void FindAllCheckBox(DependencyObject reference)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); i++)
{
var child = VisualTreeHelper.GetChild(reference, i);
if (child is CheckBox)
{
BindCheckBoxAndTextBox(child as CheckBox);
}
else
{
FindAllCheckBox(child);
}
}
}
//绑定勾选框与其对应的文本框,存入字典
private void BindCheckBoxAndTextBox(CheckBox reference)
{
DependencyObject wrapPanel = VisualTreeHelper.GetParent(reference);
DependencyObject stackPanel = VisualTreeHelper.GetParent(wrapPanel);
CheckTextBoxDic.Add(reference, FindTextBox(stackPanel));
}
//找到相应文本框并将其返回
private TextBox FindTextBox(DependencyObject reference)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(reference); i++)
{
var child = VisualTreeHelper.GetChild(reference, i);
if (child is TextBox)
{
return child as TextBox;
}
else
{
return FindTextBox(child);
}
}
return null;
}
#endregion