【问题标题】:Test if control is in GroupBox测试控件是否在 GroupBox 中
【发布时间】:2012-03-20 01:48:01
【问题描述】:

我试图弄清楚如何编写包含 if 语句的代码(特别是事件处理程序),无论发送者是否包含在 GroupBox 中。

例如,假设我有两个 GroupBox,每个都包含一个网格,然后该网格包含一个文本框。我想为“TextUpdated”编写一个事件处理程序,它可以区分事件来自哪个组框(虽然这对于只有两个文本框来说可能听起来过于复杂,但我正在处理的情况在每个组框中都有很多控件,但是事件处理程序是相同的)。

有没有办法让 sender.IsContainedIn(GroupBoxOne) 成为布尔值?因为我在每个组框中都有一个网格,所以使用 GroupBox.Parent(xyz) 似乎不起作用,因为它会将网格作为父级。

希望这是有道理的...非常感谢。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    您可以使用VisualTreeHelper.GetParent 来遍历可视化树。

    Here 是一个很好的实现方法。

    【讨论】:

      【解决方案2】:

      代码:

      // walk up the visual tree to find object of type T, starting from initial object
      public static T FindUpVisualTree<T>(DependencyObject initial) where T : DependencyObject
      {
          DependencyObject current = initial;
      
          while (current != null && current.GetType() != typeof(T))
          {
               current = VisualTreeHelper.GetParent(current);
          }
          return current as T;   
      }
      

      用法:

      Grid gridContainingButton = FindUpVisualTree<Grid>(button01);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-01-03
        • 1970-01-01
        • 1970-01-01
        • 2019-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多