Hello .
I have a situation where I need to be able to count the number of controls I have added to a stack panel. I have built this simplified solution to illustrate what I mean. When a button or label is added to the StackPanel I wish to be able to count the number buttons and labels that are in the StackPanel.
Thank you Tony.
XAML code
Code:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:CountChildElements"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="10*"/>
</Grid.RowDefinitions>
<Button x:Name="button" Content="Click to add botton" HorizontalAlignment="Left" Margin="66,37,0,0" VerticalAlignment="Top" Width="132" Height="32"/>
<ScrollViewer VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Visible" Grid.Column="0" Grid.Row="2" HorizontalAlignment="Left" Margin="12,0,0,0">
<StackPanel x:Name="StackPanel1" Grid.Column="0" Grid.Row="2" Background="DarkGray" HorizontalAlignment="Left" Height="29" VerticalAlignment="Top" Orientation="Horizontal" Grid.ColumnSpan="3"/>
</ScrollViewer>
<Button x:Name="button_Copy" Content="Click to add Label" HorizontalAlignment="Left" Margin="280,37,0,0" VerticalAlignment="Top" Width="132" Height="32"/>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="195,38.333,0,0" Grid.Row="1" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="30" Background="#FFCAA4A4"/>
<TextBox x:Name="textBox_Copy" HorizontalAlignment="Left" Height="23" Margin="426,38.333,0,0" Grid.Row="1" TextWrapping="Wrap" Text="0" VerticalAlignment="Top" Width="30" Background="#FFCAA4A4"/>
<Label x:Name="label_Copy" Content="Button count." HorizontalAlignment="Left" Margin="35,34.333,0,0" Grid.Row="1" VerticalAlignment="Top" Width="120" Background="White"/>
<Label x:Name="label_Copy1" Content="Label count." HorizontalAlignment="Left" Margin="265,34.333,0,0" Grid.Row="1" VerticalAlignment="Top" Width="120" Background="White"/>
</Grid>
</Window>
Basic Back Code
Code:
Class MainWindow
Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
'Add Button to Stack Panel 1
Dim bt As New Button
bt.Height = "20"
bt.Width = "200"
bt.Content = "Button"
bt.Background = Brushes.Green
StackPanel1.Children.Add(bt)
End Sub
Private Sub button_Copy_Click(sender As Object, e As RoutedEventArgs) Handles button_Copy.Click
'Add Label to Stack Panel 1
Dim lab As New Button
lab.Height = "20"
lab.Width = "200"
lab.Content = "Label"
lab.Background = Brushes.Yellow
StackPanel1.Children.Add(lab)
End Sub
End Class