我正在自学 WPF。我已经达到了动态添加控件的地步,并且在一些非常简单的事情上碰壁了。我编写的代码应该创建一个按钮(如下所示):
Button button = new Button() { Height = 80, Width = 150, Content = "Test" };
parentControl.Add(button);
我的问题是 parentControl
实际上叫什么?我使用的是标准 Visual Studio 2012 WPF 模板,我的主窗口名为 MainWindow
。除了模板中的内容外,窗口中没有任何对象
到目前为止我看过:
- WPF runtime control creation
- Dynamic control creation in WPF
- WPF MVVM Dynamic control creation
- Dynamic creation of control
- Where should I put WPF specific code when using MVVM?
- Steps Of Control Creation Process WPF
- Where to put code in (primarily) windowless WPF app?
我找到的最接近的: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/