このコードを使用して、ビジュアル ツリーからコントロールを取得します
public static FrameworkElement GetComponent(object child, Type t, Type bailOn)
{
if (child == null) return null;
DependencyObject control = (DependencyObject)child; // VisualTreeHelper.GetParent((DependencyObject)x);
while (control != null)
{
if (!control.Equals(child))
{
if (control.GetType() == t)
{
break;
}
}
if (control is FrameworkElement)
{
control = (control as FrameworkElement).Parent;
}
else if ((control is DataGridBoundColumn)) // data grid fucken columns
{
control = GetDataGridBoundColumnDataGrid(control);
}
if (control != null && bailOn != null && bailOn.GetType() == control.GetType())
{
return null;
}
}
// try VTH as we did not find it, as that works some times and the above does not
if (control == null)
{
control = (DependencyObject)child; // start again
while (control != null)
{
if (!control.Equals(child))
{
if (control.GetType() == t)
{
break;
}
}
if (control is FrameworkElement)
{
control = VisualTreeHelper.GetParent((control as FrameworkElement));
}
else if (control is DataGridBoundColumn)
{
control = GetDataGridBoundColumnDataGrid(control);
}
if (control != null && bailOn != null && bailOn.GetType() == control.GetType())
{
return null;
}
}
}
return control as FrameworkElement;
}
public static List<FrameworkElement> GetComponentsByType(FrameworkElement parent, Type type)
{
List<FrameworkElement> controls = new List<FrameworkElement>();
GetComponentsByTypeWorker(parent, type, controls);
return controls;
}
private static void GetComponentsByTypeWorker(FrameworkElement parent, Type type, List<FrameworkElement> controls)
{
if (parent.GetType() == type)
{
controls.Add(parent as FrameworkElement);
}
int cnt = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < cnt; i++)
{
FrameworkElement child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
if (child.GetType() == type)
{
controls.Add(child as FrameworkElement);
}
int cnt2 = VisualTreeHelper.GetChildrenCount(child);
for (int j = 0; j < cnt2; j++)
{
FrameworkElement child2 = VisualTreeHelper.GetChild(child, j) as FrameworkElement;
GetComponentsByTypeWorker(child2 as FrameworkElement, type, controls);
}
}
}