How can I find all controls within a control(WPF, C#)?
I found interesting questions about this like in How can I find WPF controls by name or type?, but I just want my method to return all controls within it. It doesn´t matter t开发者_如何学Gohe control´s name or its type as long as the method returns all possible controls he can find.
In WinForms this is very easy ... just grab the WinForms container and then prob the '.Controls' property and iterate over the collection of controls returned.
foreach (System.Windows.Forms.Control ctrl in form.Controls)
{
if (ctrl.Name == "tabPageControl")
{ // do something with 'tabPageControl object' }
{
As you can see in WinForms its dead easy to get access at the global container to return a 'ControlCollection' and then iterate through or even deeper if its a panel or something like that. Once you have found what you want are simply building a list of what can be found then do something with your list or your control.
In WPF, this is done slightly differenty. I don't have extensive WPF experience but after 15 mins of playing about I came up with this:
private void button1_Click(object sender, RoutedEventArgs e)
{
// cast out Grid object.
Grid grd = (Grid) this.Content;
// do simple testing to find out what the type is.
string s = grd.ToString();
// in VS, in debug mode, hover 'grd.Children' and Smart Tool Tip that pops
// it will tell exactly under a 'count' property how many controls there are sitting
// on the global container. For me it was just 1, my Button.
foreach (UIElement child in grd.Children)
{
// do some more testing to make sure have got the right control. pref in an If statement but anyhooo.
String sss = child.GetType().FullName;
// cast out the appropriate type.
Button myWpfButton = (Button)child;
}
}
I hope thats enought to get you started.
It depends on the type of parent control. If it is an extension of ContentControl it can only have a single child element, which is found under the Content property. If it is an extension of Panel it can have many child elements, which are found under the Children property.
There is no guarantee that any of those child elements are necessarily controls though - you will need to do some type checking to confirm whether or not they are of the type you are interested in.
This is also only for a single level of parent-child hierarchy, but should be simple enough to make recursive if you need all child controls.
精彩评论