'Add set of controls dynamically on Button Click c# wpf
I have a requirement to add a panel containing some user controls like textboxes, listviews with their own validations operating on these controls, on a button click. So every time a user clicks a button, a new panel would be generated with the above controls in the same window.
Any help, links, suggestions or pointers would be appreciated?
Solution 1:[1]
Hello I hope I understood you correctly, I have made a small sample.
XAML Codes:
<Window x:Class="My_First_WPF_App.TestWindow"
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"
mc:Ignorable="d"
Title="TestWindow" Height="450" Width="800">
<StackPanel>
<StackPanel x:Name="StackPanelTest"/>
<StackPanel Margin="0,10,0,0" Orientation="Horizontal">
<Button x:Name="AddItemsBTN" Content="Add Controls" HorizontalAlignment="Left" Margin="50,0,0,0" VerticalAlignment="Top" Click="AddItemsBTN_Click"/>
<Button x:Name="ClearItemsBTN" Margin="50,0,0,0" Content="Clear Controls" Click="ClearItemsBTN_Click"></Button>
</StackPanel>
</StackPanel>
C# Codes:
using System.Windows;
using System.Windows.Controls;
namespace My_First_WPF_App
{
/// <summary>
/// Interaction logic for TestWindow.xaml
/// </summary>
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
}
private void ClearItemsBTN_Click(object sender, RoutedEventArgs e)
{
StackPanelTest.Children.Clear();
}
private void AddItemsBTN_Click(object sender, RoutedEventArgs e)
{
StackPanel SP = new StackPanel();
SP.Orientation = Orientation.Horizontal; SP.Margin = new Thickness(50, 20, 0, 0);
TextBlock TestTextBlock = new TextBlock();
TestTextBlock.Text = "Your Test ListView: ";
ListView LV = new ListView();
Button AddItemsBTN = new Button();
AddItemsBTN.Content = "Add a new item: "; AddItemsBTN.Margin = new Thickness(20, 0, 0, 0);
AddItemsBTN.HorizontalAlignment = HorizontalAlignment.Center; AddItemsBTN.VerticalAlignment = VerticalAlignment.Center;
TextBox AddTXTBox = new TextBox(); AddTXTBox.Margin = new Thickness(10, 0, 0, 0); AddTXTBox.MinWidth = 20;
AddTXTBox.HorizontalAlignment = HorizontalAlignment.Center; AddTXTBox.VerticalAlignment = VerticalAlignment.Center;
AddItemsBTN.Click += delegate
{
LV.Items.Add(AddTXTBox.Text);
AddTXTBox.Text = "";
};
SP.Children.Add(TestTextBlock); SP.Children.Add(LV); SP.Children.Add(AddItemsBTN); SP.Children.Add(AddTXTBox);
StackPanelTest.Children.Add(SP);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dark Templar |
