【问题标题】:Loop through Groupbox in TabControl循环遍历 TabControl 中的 Groupbox
【发布时间】:2016-07-28 08:21:57
【问题描述】:

我有一个包含选项卡控件(page1、page2 和 page3)的 WPF。

在选项卡控制页面 2 中,我确实有 3 个分组框(groupbox_Agroupbox_Bgroupbox_C),每个分组框都包含3 个文本框

我可以知道循环所有文本框并清除内容的 C# 代码是什么。

【问题讨论】:

  • 你尝试过类似 groupbox_A.textbox1.clear() 的方法吗?
  • 强烈建议您使用数据绑定并清除数据
  • 初始代码使用代码作为提及 (textbox1.clear())。考虑到目前有近 60 个文本框,维护代码会很困难。

标签: c# wpf


【解决方案1】:

此函数将返回选项卡控件中的所有文本框。

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                yield return (T)child;
            }

            foreach (T childOfChild in FindVisualChildren<T>(child))
            {
                yield return childOfChild;
            }
        }
    }
}

你可以像这样枚举得到所有的文本框:

foreach (var textbox in FindVisualChildren<TextBox>(window))
{
    // do something with tb here
}

来源:Find all controls in WPF Window by type

【讨论】:

  • 感谢分享代码。看来我需要确保标签页 2 已激活,以便第 2 页中的文本框存储清晰。
  • 我确实有 stackpanel_1,方向设置为垂直。在 stackpanel_1 中,它由 stackpanel_A、B、C 和 D 组成,方向设置为水平并包含一些按钮。一些像 foreach(stackpanel_1.Children 中的 stackepanel stkpnl)这样的代码是如何工作的。
  • 这里也发生了同样的事情。见for (int i = 0; i &lt; VisualTreeHelper.GetChildrenCount(depObj); i++) {
  • 很高兴为您提供帮助。 :-)
【解决方案2】:

这看起来不是一个好方法..找到另一个逻辑来清除你的文本..但是如果你只是想知道它是如何工作的......

最简单的方法:

IEnumerable<myType> collection = control.Children.OfType<myType>();

(控件是窗口的根元素,myType 在您的情况下是 groubBox)

通过所有元素的微软方式Link

 // Enumerate all the descendants of the visual object.
 static public void EnumVisual(Visual myVisual)
 {
     for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myVisual); i++)
     {
        // Retrieve child visual at specified index value.
        Visual childVisual = (Visual)VisualTreeHelper.GetChild(myVisual, i);

        // Do processing of the child visual object.

        // Enumerate children of the child visual object.
        EnumVisual(childVisual);
    }
 }

【讨论】:

  • 您能否详细说明一下最简单的方法和 Microsoft 方法,因为我仍在努力学习 C# 技能并申请我的工作。 (我以前在 VB 中练习,就在 2 周前,我开始使用 C#。)
猜你喜欢
  • 2010-12-17
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 2020-11-17
  • 2020-06-15
相关资源
最近更新 更多