【问题标题】:How can I dynamically generate a/or some buttons in a grid? [closed]如何在网格中动态生成一个/或一些按钮? [关闭]
【发布时间】:2020-10-19 19:55:27
【问题描述】:
public MainWindow()
{
    InitializeComponent();
    Grid grid1 = new Grid();
    Button button1 = new Button();
    button1.Content = "Button";
    grid1.Children.Add(button1);
}

我想在网格中添加按钮,但不知何故窗口是空的,我不知道为什么。

【问题讨论】:

标签: c# wpf


【解决方案1】:

您看不到按钮或网格的原因是您没有将 Grid 分配给 MainWindow 的 Content 属性。

您应该在设计器中添加网格控件,以便将其定义为类的成员。之后,您可以像以前一样将按钮添加到网格中,而无需重新实例化网格。

工作示例:

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        Button button1 = new Button();
        button1.Content = "Button";
        gridTest.Children.Add(button1);            
    }
}

MainWindow.xaml

<Window x:Class="WpfApp2.MainWindow"
    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:WpfApp2"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">

    <Grid x:Name="gridTest"/>
</Window>

【讨论】:

  • 非常感谢
  • @Syst3m4nia 从您的回复中,我了解到该答案对解决问题很有用。您能否投票/将答案标记为已接受?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 2017-06-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多