【问题标题】:How can I get the parent Popup for a UIElement?如何获取 UIElement 的父弹出窗口?
【发布时间】:2010-01-05 16:45:31
【问题描述】:

我有两个关于以下标记的问题:

<Popup>
    <Button x:Name="button"/>
</Popup>
  1. 为什么VisualTreeHelper.GetParent(button) 返回null?
  2. 如何获得Popup 的父级UIElement?

【问题讨论】:

    标签: silverlight popup uielement


    【解决方案1】:

    您不是通过VisualTree,而是尝试了一个while循环来遍历元素的.Parents?

        private void TryClosePopupParent(object o)
        {
            while (o != null)
            {
                Popup p = (o as Popup);
                if(p == null)
                {
                    o = (o as FrameworkElement).Parent;
                }
                else 
                {
                    p.IsOpen = false;
                    break;
                }
            }
        }
    

    我从未在 没有有 PopUp 作为父级的东西上测试过它,但它对我有用。

    【讨论】:

      【解决方案2】:
      1. 因为Button 仅在显示弹出窗口时添加到可视化树中。

      2. 嗯...棘手...

      编辑

      以下假设您的弹出窗口是在 UserControl 的 XAML 中定义的,因此虽然它的子窗口可能不在可视化树中,但弹出窗口原语控件是。

      重复使用我之前发布的一些代码(我真的必须给我一个博客)。

      public static class VisualTreeEnumeration
      {
          public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
          {
              int count = VisualTreeHelper.GetChildrenCount(root);
              for (int i = 0; i < count; i++)
              {
                  var child = VisualTreeHelper.GetChild(root, i);
                  yield return child;
                  foreach (var descendent in Descendents(child))
                      yield return descendent;
              }
          }
      }
      

      这为DependencyObject 添加了一个扩展方法,它使用VisualTreeHelper 来统一搜索添加到视觉树中的对象。所以在后面的用户控件代码中你可以这样做:-

      var popup this.Descendents()
              .OfType<Popup>()
              .Where(p => p.Child == button)
              .FirstOrDefault();
      

      这将找到Popup,它是“按钮”的父级。

      【讨论】:

      • 即使打开弹出 GetParent 方法返回 null
      • 嗯...是的,这是真的,它位于树的顶部,显示在现有视觉效果的顶部。因此,偏移量是相对于 Silverlight 控件本身的。
      【解决方案3】:

      Popup 控制有时很烦人。而且我现在不知道为什么VisualTreeHelper.GetParent(button) 返回null。但是对于第二个this 可能会有所帮助。

      【讨论】:

        【解决方案4】:

        zihotki 的解决方案看起来很有希望(我还没有测试过)。

        虽然VisualTreeHelper.GetParent(button) 返回null,但您可以使用button.Parent,它应该会给您弹出对象。

        【讨论】:

        • @DaveClemmer:哇 - 有没有用于编辑问题和每个答案的徽章?
        【解决方案5】:

        确保PopUp 附加到VisualTree。在备注部分找到更多信息 http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.popup(v=vs.95).aspx

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-01
          相关资源
          最近更新 更多