WPF动态控制创建代码的放置位置

时间:2012-12-30 22:07:48

标签: 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

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

1 个答案:

答案 0 :(得分:4)

我想我理解你的问题。如果你的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>