【问题标题】:Clear all TextBox in Window清除窗口中的所有文本框
【发布时间】:2014-06-08 22:29:10
【问题描述】:

我正在用 c#(WPF) 编程。我有很多nested controls。我想clear all 我的应用程序中的 TextBox 控件。很难通过他们的名字访问它们。有什么方法可以访问它们recursively 并清除它们吗?

例如这样的事情:

public void ClearAll(Control c)
{
    if(c is TextBox)
    {
        ((TextBox)c).Clear();
        return;
    }

    foreach(Control child in GetChild(c))
    {
        ClearAll(child);
    }
}

【问题讨论】:

  • TextBox 显示您的XAML,然后使用CommandBindings 或类似的东西更容易清除它们。
  • 你可以看看这个答案stackoverflow.com/questions/974598/…
  • WPF 中的规则 #1。 “WPF 不是 WinForms”!您可能应该开始研究绑定以及如何设置它们。您应该(几乎)永远不必通过名称访问控件或在代码中对其进行操作。几乎所有你能想到的修改都可以通过绑定来实现。
  • @Babak.Abad 如果您刚刚从 WinForms 迁移,现在是学习它们的最佳时机 :) 这将使您的生活更轻松,而无需递归地查找所有控件并一一清除它们,而是使用一个命令来清除它们。国际海事组织。
  • 更一般地说,对 MVVM 以及它如何应用于 WPF 进行一些研究。

标签: c# wpf controls wpf-controls


【解决方案1】:

VisualTreeHelper 类派上用场。你可以这样使用它:

static public void TraverseVisualTree(Visual myMainWindow)
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(myMainWindow);
        for (int i = 0; i < childrenCount; i++)
        {
            var visualChild = (Visual)VisualTreeHelper.GetChild(myMainWindow, i);
            if (visualChild is TextBox)
            {
                TextBox tb = (TextBox)visualChild;
                tb.Clear();
            }
            TraverseVisualTree(visualChild);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多