ユーザコントロールから親ウィンドウにアクセスしようとしています。ユーザコントロールから親ウィンドウにアクセス
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
このコードでは、userControl1
をメイングリッドにロードします。
userControl1
のボタンをクリックすると、userControl2
をメインウィンドウのmainGrid
にロードしますか?
ユーザコントロールから親ウィンドウにアクセスしようとしています。ユーザコントロールから親ウィンドウにアクセス
userControl1 uc1 = new userControl1();
mainGrid.Children.Add(uc1);
このコードでは、userControl1
をメイングリッドにロードします。
userControl1
のボタンをクリックすると、userControl2
をメインウィンドウのmainGrid
にロードしますか?
あなたは、メインウィンドウの静的インスタンスを作成します
Window yourParentWindow = Window.GetWindow(userControl1);
を試してみましたが、あなたは単にあなたのユーザーコントロールでそれを呼び出すことができます。
は、この例を参照してください:
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)
}
}
このソリューションは、問題のウィンドウが複数同時に開いている場合は機能しません。あなたのコメントでは、これが機能するための "メインウィンドウ"を参照していることが分かります。ただし、これはすべてのウィンドウタイプに適用されるわけではありません。 – curob
ありがとうございました。私は別のソリューション
((this.Parent) as Window).Content = new userControl2();
これは完全にこれがルートレベルウィンドウを取得
注意:ここでは、コントロールの親が常にWindowインスタンスであることを前提としています。 – Crono
に動作されました:
Window parentWindow = Application.Current.MainWindow
または直接の親ウィンドウ
Window parentWindow = Window.GetWindow(this);
のみ理由を提案
あなたは右の型にキャストしていないので、あなたのための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
内で動的に検索することをお勧めします。
はい、私はしようとしましたが、その後どのようにmainControlにuserControl2をロードできますか? –
ウィンドウyourParentWindow = Window.GetWindow(userControl1); yourParentWindow.mainGrid.children.add(新しいuserControl2); はこの正しいコードですか? –
yourParentWindow.mainGrid.Children.Add(new userControl2()) –