I have a User Control, containing a Grid, containing a child control.
I want to get a reference to the child control from the code behind for the User Control.
This is what I have:
var childControl = (MyChildControlType)this.Grid.Children.Single(c => (string) c.GetValue(NameProperty) == "MyChildControlNameFromXAMLNameAttribute");
Ugly as a run over garbage can lid.
What is a neater way to do this?
You could either go with the name-hunting, along the lines of what's been suggested already:
var childControl = (MyChildControlType)this.Grid.FindName("MyChildControlNameEtc");
Or, if you wanted a more generic approach to what you're already trying (eg if you want to look up by a different property), you could try:
var childControl = (MyChildControlType)this.Grid.Children.OfType<FrameworkElement>().Single(f => f.Name == "Blah");
or
var childControl = (MyChildControlType)this.Grid.Children.OfType<MyChildControlType>().Single(f => f.Name == "Blah");
Or you could use the VisualTreeHelper, which would work with non-Grids, and would particularly work nicely if you needed to recurse down the visual tree:
for(int i = 0; i < VisualTreeHelper.GetChildrenCount(this.Grid); ++i)
{
var child = VisualTreeHelper.GetChild(this.Grid, i) as FrameworkElement;
if (child != null && child.Name == "Blah")
return child;
}
But really if you can just name it and access it from the codebehind normally like what John Bowen said that's by far the easiest.
Assigning a Name or x:Name to an element in XAML (unless it is inside a template) makes that element accessible from code-behind as a field with that name. So this is basically already declared and populated for you during InitializeComponent:
MyChildControlType MyChildControlNameFromXAMLNameAttribute;
and you can use it directly:
MyChildControlNameFromXAMLNameAttribute.Visibility = Visibility.Hidden;
可能是这样,给您的childControl输入x:Name
var childControl = (MyChildControlType)MyGridNameFromXAMLNameAttribute.FindName("MyChildControlNameFromXAMLNameAttribute");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.