我有一個MainWindow,並且在這個MainWindow中有一個UserControl加載。 MainWindow包含一個StackPanel。現在我想從UserControl向該StackPanel添加一個按鈕。在WPF/C中的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中呢? – OBSCURE