2013-04-26 13 views
19

ユーザコントロールから親ウィンドウにアクセスしようとしています。ユーザコントロールから親ウィンドウにアクセス

userControl1 uc1 = new userControl1(); 

mainGrid.Children.Add(uc1); 

このコードでは、userControl1をメイングリッドにロードします。

userControl1のボタンをクリックすると、userControl2をメインウィンドウのmainGridにロードしますか?

答えて

40

あなたは、メインウィンドウの静的インスタンスを作成します

Window yourParentWindow = Window.GetWindow(userControl1); 
+0

はい、私はしようとしましたが、その後どのようにmainControlにuserControl2をロードできますか? –

+0

ウィンドウyourParentWindow = Window.GetWindow(userControl1); yourParentWindow.mainGrid.children.add(新しいuserControl2); はこの正しいコードですか? –

+0

yourParentWindow.mainGrid.Children.Add(new userControl2()) –

0

を試してみましたが、あなたは単にあなたのユーザーコントロールでそれを呼び出すことができます。

は、この例を参照してください:

Window1.cs

public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
      _Window1 = this; 
     } 
     public static Window1 _Window1 = new Window1(); 

    } 

UserControl1.CS

public partial class UserControl1 : UserControl 
    { 
     public UserControl1() 
     { 
      InitializeComponent(); 

     } 
     private void AddControl() 
     { 
      Window1._Window1.MainGrid.Children.Add(usercontrol2) 
     } 
    } 
+0

このソリューションは、問題のウィンドウが複数同時に開いている場合は機能しません。あなたのコメントでは、これが機能するための "メインウィンドウ"を参照していることが分かります。ただし、これはすべてのウィンドウタイプに適用されるわけではありません。 – curob

1

ありがとうございました。私は別のソリューション

((this.Parent) as Window).Content = new userControl2(); 

これは完全にこれがルートレベルウィンドウを取得

+2

注意:ここでは、コントロールの親が常にWindowインスタンスであることを前提としています。 – Crono

11

に動作されました:

Window parentWindow = Application.Current.MainWindow 

または直接の親ウィンドウ

Window parentWindow = Window.GetWindow(this); 
0

のみ理由を提案

あなたは右の型にキャストしていないので、あなたのための

didntの作業がある :

var win = Window.GetWindow(this) as MyCustomWindowType; 

if (win != null) { 
    win.DoMyCustomWhatEver() 
} else { 
    ReportError("Tough luck, this control works only in descendants of MyCustomWindowType"); 
} 

はWindowsの種類とあなたのコントロール間方法よりカップリングがなければならない場合を除き、私はあなたの考えます悪いデザインに近づく。

私は、コントロールが動作するグリッドをコンストラクタパラメータとして渡し、それをプロパティにしたり、適切な(ルート?)グリッドをWindow内で動的に検索することをお勧めします。

関連する問題