在WPF中,位于模板中的控件无法在后台直接通过Name属性获取;
可通过以下方式获取:
public T GetVisualChild<T>(DependencyObject parent, Func<T, bool> predicate) where T : Visual
{
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
DependencyObject v = (DependencyObject)VisualTreeHelper.GetChild(parent, i);
T child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v, predicate);
if (child != null)
{
return child;
}
}
else
{
if (predicate(child))
{
return child;
}
}
}
return null;
}
CheckBox chb = GetVisualChild<CheckBox>(DG, v => v.Name == "cbbSelALL");
if (null != chb)
{
chb.IsChecked = false;
}
T:想要获取的控件的类型;
DG:包含想要获取的控件的控件名称;