How about using UserControl?
Right click on the project and select Add=>New Item=>User Control(WPF).
I added a button and two TextBlock as examples.
<UserControl x:Class="WpfApp2.MyNewUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
d:DesignHeight="200" d:DesignWidth="200">
<Grid Background="AliceBlue">
<TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="68,46,0,0" TextWrapping="Wrap" Text="textBlock" VerticalAlignment="Top"/>
<TextBlock x:Name="textBlock1" HorizontalAlignment="Left" Margin="68,77,0,0" TextWrapping="Wrap" Text="textBlock1" VerticalAlignment="Top"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="34,19,0,0" VerticalAlignment="Top" Width="75"/>
</Grid>
</UserControl>
Use it in MainWindow.
<Grid>
<local:MyNewUC Width="200" Height="200" x:Name="myUC"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="578,172,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
</Grid>
Make sure the namespace has been added:
xmlns:local="clr-namespace:WpfApp2"
Call it in the code:
private void button_Click(object sender, RoutedEventArgs e)
{
myUC.textBlock1.Text = "testTextBlock";
myUC.button.Content = "test";
}
Update:
Is the number of dynamically added controls equal to the number of items in the list?
Is their order one-to-one correspondence? For example, the first item corresponds to the first control, the second item corresponds to the second control, and so on.
If so, will the following code help?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
CreateUC(3);
}
private void CreateUC(int n)
{
for (int i = 0; i < n; i++)
{
MyNewUC myNewUC = new MyNewUC() { Width = 200, Height = 150,Margin =new Thickness((i+1)*200,50,0,0)};
mainGrid.Children.Add(myNewUC);
}
}
private void button_Click(object sender, RoutedEventArgs e)
{
List<MyClass> myClasses = new List<MyClass>();
myClasses.Add(new MyClass() { Name = "Timon", Age = 26 });
myClasses.Add(new MyClass() { Name = "Tom", Age = 6 });
myClasses.Add(new MyClass() { Name = "Jerry", Age = 7 });
List<MyNewUC> myNewUCs = mainGrid.Children.OfType<MyNewUC>().ToList();
for (int i = 0; i < myClasses.Count; i++)
{
myNewUCs[i].textBlock.Text = myClasses[i].Name;
myNewUCs[i].textBlock1.Text = myClasses[i].Age.ToString();
}
}
}
class MyClass
{
public string Name { get; set; }
public int Age { get; set; }
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.