Skip to main content
 首页 » 编程设计

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

2024年02月20日12itcoder

我正在自学 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>