WPF階層内のオブジェクトのベース親にアクセスするにはどうすればよいですか?
質問
WPFオブジェクトの奥深く hiearchy Windowオブジェクトを作成します。
ただし、このウィンドウオブジェクトの所有者をベースウィンドウオブジェクトにしたい。
「ツリーを登る」ことを試みました次のタイプのコードを使用しますが、このアプローチは準最適のようです:
(((((((TabGroupPane)((ContentPane) this.Parent).Parent).Parent as
SplitPane).Parent as DocumentContentHost).Parent as
XamDockManager).Parent as ContentControl).Parent as
StackPanel).Parent...
ベースWindowオブジェクトにアクセスするにはどうすればよいですか
このようなことを考えています:
擬似コード:
Window baseWindow = this.BaseParent as Window;
解決
すべてのタイプで機能するアプローチは、必要なタイプのノードが見つかるまで論理ツリーをさかのぼることです。
Window baseWindow = FindLogicalParent<Window>(this);
このメソッドはフレームワークに存在しないため、実装は次のとおりです。
internal static T FindLogicalParent<T>(DependencyObject obj)
where T : DependencyObject
{
DependencyObject parent = obj;
while (parent != null)
{
T correctlyTyped = parent as T;
if (correctlyTyped != null)
return correctlyTyped;
parent = LogicalTreeHelper.GetParent(parent);
}
return null;
}
Window
の場合、具体的には次を使用できます。
Window.GetWindow(this);
他のヒント
これに答えさせてください:
Window baseWindow = Application.Current.Windows[0];
所属していません StackOverflow