Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get children of a WPF container by type?

How can I get the child controls of type ComboBox in MyContainer Grid in WPF?

<Grid x:Name="MyContainer">                         <Label Content="Name"  Name="label1"  />     <Label Content="State" Name="label2"  />     <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox1"/>     <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox3" />     <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox4" /> </Grid> 

This line gives me an error:

var myCombobox = this.MyContainer.Children.GetType(ComboBox); 
like image 255
ArchieTiger Avatar asked Apr 23 '12 10:04

ArchieTiger


People also ask

Where is parent control in WPF?

Use MessageBox to display a dialog box that appears in the caller's central, obviously, to do this, MessageBox must get the parent control, so as to calculate the center position.

What is container WPF?

WPF supports a rich set of control containers derived from the base Panel class. These include Canvas, DockPanel, StackPanel, WrapPanel, and Grid. Silverlight is a little more restricted, owing to its need to keep the runtime install as light as possible, and supports only Canvas, Grid, and StackPanel.


1 Answers

This extension method will search recursively for child elements of the desired type:

public static T GetChildOfType<T>(this DependencyObject depObj)      where T : DependencyObject {     if (depObj == null) return null;      for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)     {         var child = VisualTreeHelper.GetChild(depObj, i);          var result = (child as T) ?? GetChildOfType<T>(child);         if (result != null) return result;     }     return null; } 

So using that you can ask for MyContainer.GetChildOfType<ComboBox>().

like image 120
Matt Hamilton Avatar answered Sep 17 '22 19:09

Matt Hamilton