Use reflection to look for controls in side a composite wpf control
I trying to write a method that will look at a wpf usercontrol that contains other wpf usercontrol elements. For example one of the usercontrols contains a datagrid with columns added using xaml. I want to be able to manipulate a named column in the datagrid. I'm trying开发者_如何学C to use reflection and I can't find a way to get the internal controls. I've tried the different get methods (GetProeprties, GetMembers, GetFields) but can't find a collection of internal usercontrols. Any ideas would be appreciated.
Have you tried using FindName
?
var col = uc.FindName("MyColumn") as DataGridColumn;
Edit: This works in simple cases but for nested UserControls it may not. This being the case you could employ it recursively, here's some sketchy implementation:
public static object FindNamedObject(FrameworkElement container, string name)
{
var target = container.FindName(name);
if (target == null)
{
int count = VisualTreeHelper.GetChildrenCount(container);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(container, i) as FrameworkElement;
if (child != null)
{
target = FindNamedObject(child, name);
if (target != null)
{
break;
}
}
}
}
return target;
}
精彩评论