【发布时间】:2014-03-23 05:40:01
【问题描述】:
我有一个 MainWindow,在这个 MainWindow 中我加载了一个 UserControl。 MainWindow 包含一个 StackPanel。现在我想从 UserControl 向 StackPanel 添加一个按钮。
如果我直接添加它,它可以工作(来自 MainWindow)——但不能来自 UserControl。
例子:
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
var myTestRadioButton = new RadioButton
{
Name = "TestRadioButton",
Height = 31.5,
Width = 140,
};
MyStackPanel.Children.Add(myTestRadioButton);
}
作品
UserControl1.xaml.cs
public UserControl1()
{
InitializeComponent();
var parentWindow = new MainWindow();
var myTestRadioButton = new RadioButton
{
Name = "TestRadioButton",
Height = 31.5,
Width = 140,
};
parentWindow.MyStackPanel.Children.Add(myTestRadioButton);
}
没用。
我也尝试过创建父窗口的静态实例...
有趣的是 -> 我没有收到错误消息或类似的东西......它只是不起作用(例如按钮不显示......)
请帮忙 :) :) :)
【问题讨论】:
-
不要在 WPF 的过程代码中创建或操作 UI 元素。这就是 XAML 的用途。
-
最好的方法是为您的用户控件创建一个事件,在您的父表单中订阅它并在那里完成您的工作。
-
那我将如何在 XAML 中解决这个问题?
-
问题是——我想用创建的 buttons(如浏览器中的标签)来实现像标签控件(但带有按钮)这样的行为——但按钮是在主窗口中,它们的内容在 UserControl 中 - 但我仍然想像标签一样切换 ^^
标签: c# wpf xaml user-controls