使用代码动态添加WPF控件

时间:2015-04-08 09:57:14

标签: c# wpf

我是WPF的新手,遇到了一种情况,我认为动态添加控件会很好。

但我不知道是否可以动态使用代码。我想使用代码

添加以下内容
<WrapPanel Height="39">
      <TextBox Width="93" Margin="-1,5,0,0"></TextBox>
      <TextBox Width="76" Margin="0,5,0,0"></TextBox>
      <TextBox Width="70" Margin="0,5,0,0"></TextBox>
      <TextBox Width="70" Margin="0,5,0,0"></TextBox>
      <TextBox Width="127" Margin="0,5,0,0"></TextBox>
      <TextBox Width="100" Margin="0,5,0,0"/>
</WrapPanel>

我尝试了THIS方法,但它无效

1 个答案:

答案 0 :(得分:0)

尝试以下代码

 var panel = new WrapPanel() { Height = 39 };
            panel.Children.Add(new TextBox() { Width = 93, Margin = new Thickness(-1, 5, 0, 0) });
            panel.Children.Add(new TextBox() { Width = 76, Margin = new Thickness(0, 5, 0, 0) });
            panel.Children.Add(new TextBox() { Width = 70, Margin = new Thickness(0, 5, 0, 0) });
            panel.Children.Add(new TextBox() { Width = 70, Margin = new Thickness(0, 5, 0, 0) });
            panel.Children.Add(new TextBox() { Width = 127, Margin = new Thickness(0, 5, 0, 0) });
            panel.Children.Add(new TextBox() { Width = 100, Margin = new Thickness(0, 5, 0, 0) });
            this.Content = panel;