How do you access the children of a WPF Canvas class?
How do you access the children of a WPF Canvas class?
It is a cool class and I like how you are able to add children. But once they are there, how to you look at them for reading their state and content. I know it is easy if you put the children in XAML. But what if you have added children to the canvas dynamically at run time?
Re: How do you access the children of a WPF Canvas class?
This will add two buttons to the Canvas at runtime. On the "Get Children" button click, it will loop through the children and display the text of the Button.
XAML:
Code:
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="318" Width="489">
<Grid>
<Canvas
x:Name="canvas1"
Height="100"
HorizontalAlignment="Left"
Margin="116,62,0,0"
VerticalAlignment="Top"
Width="200">
</Canvas>
<Button
x:Name="btnGetChildren"
Content="Get Children"
Height="23"
Margin="174,209,218,47"
Width="75"
Click="btnGetChildren_Click" />
</Grid>
</Window>
Code:
Code:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window1_Loaded);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
StackPanel sp = new StackPanel();
sp.Orientation = Orientation.Vertical;
Button b = new Button();
b.Content = "Button 1";
Button b1 = new Button();
b1.Content = "Button 2";
sp.Children.Add(b);
sp.Children.Add(b1);
canvas1.Children.Add(sp);
}
private void btnGetChildren_Click(object sender, RoutedEventArgs e)
{
foreach (UIElement element in canvas1.Children)
{
if (element is StackPanel)
{
StackPanel sp = element as StackPanel;
foreach (UIElement spElement in sp.Children)
{
if (spElement is Button)
{
Button b = spElement as Button;
MessageBox.Show(b.Content.ToString());
}
}
}
}
}
}
Re: How do you access the children of a WPF Canvas class?
In my opinion, trying to get all the children is kind of missing the point of WPF.
If you need to dynamically add controls, create an observable collection and bind to the collection. Then perform operations on the collection (rather than from the canvas/WPF point of view).
Sure you can iterate through the controls, but this really should be only used in very specialized applications.