【问题标题】:Dynamically added controls in stackpanel is not visible in wpf c#在 wpf c# 中,stackpanel 中动态添加的控件不可见
【发布时间】:2016-04-14 14:08:25
【问题描述】:

我根据堆栈面板内的按钮单击动态添加文本框。但文本框在 UI 中不可见。 这是用于在 stackpanel 中创建文本框的代码。

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

为什么它不可见..??这里是 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>

【问题讨论】:

  • 请推送您的 xaml 代码。我认为问题可能出在您的 panel1 的“高度”上。或者您的 panel1 可能被其他控件覆盖。
  • 你的代码是正确的,应该是其他地方有问题。
  • 更新了 xaml 代码

标签: c# wpf xaml stackpanel


【解决方案1】:

如果您要动态添加控件,请不要限制要添加到的容器的高度(甚至宽度)。

更新您的 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>

此外,一旦您添加了一个新的孩子,请确保您正在更新 StackPanel 布局。

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

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

【讨论】:

    【解决方案2】:

    在您的 xaml 代码中,您的“面板”中有一个堆栈面板,它将是“面板”的第一个孩子。

    它的高度是 144px。你的“面板 1”是 151 像素。

    因此,当您将文本框添加到“面板”时,它们将显示在 144 像素堆栈面板的后面。

    只有 7px 可以显示它们。所以它们不会显示在您的窗口上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多