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: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: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()); } } } } } }




Reply With Quote