简体   繁体   English

在wpf c#中看不到stackpanel中动态添加的控件

[英]Dynamically added controls in stackpanel is not visible in wpf c#

I am dynamically adding textboxes based on a button click inside the stackpanel.But the textboxes are not visible in the UI . 我基于stackpanel内部的按钮单击动态添加文本框。但是文本框在UI中不可见。 Here is the code used for creating textboxs inside stackpanel. 以下是用于在stackpanel中创建文本框的代码。

 public void GenerateControls()
 {
     TextBox txtNumber = new TextBox();
     txtNumber.Name = "txtNumber";
     txtNumber.Text = "1776";
     txtNumber.Background= Brushes.Red;
     panel1.Children.Add(txtNumber);
 }

why its not visible..??and here is the XAML part of stackpanel 为什么它不可见.. ??这里是stackpanel的XAML部分

<StackPanel Name="panel1" Grid.Column="1" HorizontalAlignment="Left" Height="151" Margin="427,60,0,0" Grid.Row="2" VerticalAlignment="Top" Width="216">
    <StackPanel Height="144">

    </StackPanel>
</StackPanel>

If you are going to be adding controls dynamically, do not restrict the height (or even width) of the container you are adding to. 如果要动态添加控件,请不要限制要添加的容器的高度(甚至宽度)。

Update your XAML to have auto height/width. 更新您的XAML以具有自动高度/宽度。

<StackPanel Name="panel1" 
            Grid.Column="1"
            Height="Auto"
            Width="Auto" 
            Margin="427,60,0,0" 
            Grid.Row="2" 
            VerticalAlignment="Top"
            HorizontalAlignment="Left" >
    <StackPanel Height="144">

    </StackPanel>
</StackPanel>

Also, once you add a new child, make sure you are updating the StackPanel layout. 此外,添加新子项后,请确保更新StackPanel布局。

public void GenerateControls()
{
    TextBox txtNumber = new TextBox();
    txtNumber.Name = "txtNumber";
    txtNumber.Text = "1776";
    txtNumber.Background= Brushes.Red;

    panel1.Children.Add(txtNumber);
    panel1.UpdateLayout();
}

In your xaml code, there is a stackpanel in your 'panel', it will be the 1st child of 'panel'. 在您的xaml代码中,“面板”中有一个堆栈面板,它将是“面板”的第一个子节点。

And its height is 144px. 它的高度是144px。 your 'panel1' is 151 px. 你的'panel1'是151像素。

So when you add textboxes into 'panel', they will be displayed behind the 144px stackpanel. 因此,当您将文本框添加到“面板”时,它们将显示在144px堆栈面板后面。

There is only 7px to display them. 显示它们只有7px。 So they will not display on your window. 因此它们不会显示在您的窗口上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM