【问题标题】:How can I access the base parent of an object in a WPF hierarchy?如何访问 WPF 层次结构中对象的基本父级?
【发布时间】:2009-09-18 11:58:33
【问题描述】:

深入我的 WPF 对象 hiarchy 我创建了一个 Window 对象。

但是,我希望此窗口对象的 所有者基础 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;

【问题讨论】:

    标签: c# wpf hierarchy


    【解决方案1】:

    一种适用于所有类型的方法是沿着逻辑树向上走,直到找到所需类型的节点:

    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);
    

    【讨论】:

      【解决方案2】:

      请允许我回答这个问题:

      Window baseWindow = Application.Current.Windows[0];
      

      【讨论】:

      • 假设您只有一个窗口。
      猜你喜欢
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多