【问题标题】:Find Parent of Control by Name按名称查找父控件
【发布时间】:2013-03-04 09:18:02
【问题描述】:

当在 xaml 代码中设置名称时,有没有办法通过名称找到 WPF 控件的父级?

【问题讨论】:

    标签: wpf controls parent


    【解决方案1】:

    试试这个,

    element = VisualTreeHelper.GetParent(element) as UIElement;   
    

    在哪里, 元素是孩子 - 你需要得到谁的父母。

    【讨论】:

      【解决方案2】:

      实际上,我可以通过使用 VisualTreeHelper 按名称和类型递归查找父控件来做到这一点。

          /// <summary>
          /// Recursively finds the specified named parent in a control hierarchy
          /// </summary>
          /// <typeparam name="T">The type of the targeted Find</typeparam>
          /// <param name="child">The child control to start with</param>
          /// <param name="parentName">The name of the parent to find</param>
          /// <returns></returns>
          private static T FindParent<T>(DependencyObject child, string parentName)
              where T : DependencyObject
          {
              if (child == null) return null;
      
              T foundParent = null;
              var currentParent = VisualTreeHelper.GetParent(child);
      
              do
              {
                  var frameworkElement = currentParent as FrameworkElement;
                  if(frameworkElement.Name == parentName && frameworkElement is T)
                  {
                      foundParent = (T) currentParent;
                      break;
                  }
      
                  currentParent = VisualTreeHelper.GetParent(currentParent);
      
              } while (currentParent != null);
      
              return foundParent;
          }
      

      【讨论】:

        【解决方案3】:

        在代码中,您可以使用VisualTreeHelper 遍历控件的可视化树。您可以像往常一样通过代码隐藏的名称来识别控件。

        如果您想直接从 XAML 使用它,我会尝试实现一个自定义的“值转换器”,您可以实现它来找到满足您要求的父控件,例如具有某种类型。

        如果您不想使用值转换器,因为它不是“真正的”转换操作,您可以实现一个“ParentSearcher”类作为依赖对象,它为“输入控件”提供依赖属性,您的搜索谓词和输出控件并在 XAML 中使用它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-23
          • 2011-05-27
          • 2010-10-12
          相关资源
          最近更新 更多