c# - 在哪里放置 WPF 动态控件创建代码

标签 c# wpf button

我正在自学 WPF。我已经达到了动态添加控件的地步,并且在一些非常简单的事情上碰壁了。我编写的代码应该创建一个按钮(如下所示):

Button button = new Button() { Height = 80, Width = 150, Content = "Test" };
parentControl.Add(button);

我的问题是 parentControl 实际上叫什么?我使用的是标准 Visual Studio 2012 WPF 模板,我的主窗口名为 MainWindow。除了模板中的内容外,窗口中没有任何对象

到目前为止我看过:

我找到的最接近的:WPF runtime control creation .

所有这些问题都假设你知道这样一个基本的东西,但我不知道。请帮忙。

最佳答案

我想我明白你的问题了。如果您的 XAML 代码如下所示:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
</Window>

那么你的代码隐藏应该是这样的:

public MainWindow()
{
    InitializeComponent();
    Button button = new Button() { Height = 80, Width = 150, Content = "Test" };
    //In case you want to add other controls;
    //You should still really use XAML for this.
    var grid = new Grid();
    grid.Children.Add(button);
    Content = grid;
}

但是,我强烈建议您尽可能多地使用 XAML。此外,我不会从构造函数添加控件,但会使用窗口的 Loaded 事件。您可以从构造函数的代码隐藏中或直接在 XAML 中向事件添加处理程序。如果您想在 XAML 中获得与上述相同的结果,您的代码将是:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Height="80" Width="180" Content="Test"/>
    </Grid>
</Window>

关于c# - 在哪里放置 WPF 动态控件创建代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14095167/

相关文章:

c# - 删除 FileSystemWatcher 正在监视的文件夹

c# - 使用 C# 的数学向量在堆栈上还是堆上更快?

wpf - .net 4 中的 MVVM 有什么新功能?

Java fx 缓慢移动的图像

c# - 在 WPF 中,只有一个按钮的图标可以点击,而不是整个按钮

javascript - 这个按钮是怎么回事?

c# - .NET XmlDocument LoadXML 和实体

c# - 在母版页中添加内容页的控件

c# - MaterialDesign ColorZone 高度尺寸

c# - 将变量从嵌入式 Web 浏览器传递到应用程序