我想在运行时创建x标签和文本框。 x是整数。对于前者如果x = 4,我想在MainWindow中创建4个标签和4个文本框。我怎么能这样做?
答案 0 :(得分:-1)
这个怎么样......
public partial class DynamicControlsBench : Window
{
public DynamicControlsBench()
{
InitializeComponent();
int x = 4;
for(int i = 0; i < x; i++)
{
Label lb = new Label();
lb.Content = "Label " + i;
stackPanel.Children.Add(lb);
TextBox tb = new TextBox();
tb.Text = "Text Box " + i;
stackPanel.Children.Add(tb);
}
}
}
WHERE ...
<Window x:Class="WPFBench.DynamicControlsBench"
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:WPFBench"
mc:Ignorable="d"
Title="DynamicControlsBench" Height="300" Width="300">
<StackPanel Name="stackPanel">
</StackPanel>
</Window>