2014-02-21 101 views
1

我有一個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); 
    } 

不起作用。

我試圖創建父窗口的靜態實例,以及...

有趣的是 - >我沒有得到任何錯誤信息或類似的..它只是不工作(如按鈕犯規表演的東西起來......)

請幫助:) :) :)

+1

**不要創建和操縱在WPF程序代碼UI元素。這就是XAML的用途。** –

+0

最好的辦法是爲你的用戶控件創建一個事件,在你的父窗體中訂閱它並在那裏完成你的工作。 –

+0

那麼我如何解決在XAML中呢? – OBSCURE

回答

0

這樣var parentWindow = new MainWindow();要創建在用戶控件不是你目前的主窗口的引用的new window

public UserControl1() 
     { 
      InitializeComponent(); 

      var parentWindow = new MainWindow(); 

      var myTestRadioButton = new RadioButton 
      { 
       Name = "TestRadioButton", 
       Height = 31.5, 
       Width = 140, 
      }; 
     //just add something like this 
     public void AddChildControl(Window MyWindow) 
     { 
       MyWindow.MyStackPanel.Children.Add(myTestRadioButton); 
     } 

    } 

變化從用戶控制

public MainWindow() 
    { 
     InitializeComponent(); 

     var myTestRadioButton = new RadioButton 
     { 
      Name = "TestRadioButton", 
      Height = 31.5, 
      Width = 140, 
     }; 

      var usercontrol1= new UserControl1() ; 
      usercontrol.AddChildControl(this); 

    } 
0

的主窗口,你使窗口的新實例。 (KB的SSE回答)這個不能工作,反正

如果你真的(不管是什麼)需要dynamicaly GUI,你應該使用另一種方法:

你可能想有你的用戶控件內一個StackPanel

<Stackpanel x:Name="myStack"/> 

代碼隱藏:

Usercontrol() 
{ 
myStack.Children.Add(new WhateverControl()); 
} 
相關問題