簡體   English   中英

清除窗口上的文本框控件

[英]Clear Textbox Controls on Window

我需要以某種方式遍歷UWP項目的MainWindow上的所有控件。 我最初的想法是,這將是在我的window.Controls上的一個簡單的foreach,但這在UWP中並不存在。

我瀏覽了一下,在這里發現了一個類似的問題但是當我嘗試該代碼時,該代碼似乎也不起作用。 它成功地遍歷了整個Window,只是發現所找到的對象根本沒有,即使我可以清楚地看到它正在穿過Grid等。

有沒有辦法使用C#在UWP中做到這一點? 我試圖尋找一個VisualTreeHelper來做到這一點,但無論如何都沒有成功。 任何幫助表示贊賞!

您可以使用MSDN文檔中的以下方法從頁面中獲取所有文本框:

internal static void FindChildren<T>(List<T> results, DependencyObject startNode)
  where T : DependencyObject
{
    int count = VisualTreeHelper.GetChildrenCount(startNode);
    for (int i = 0; i < count; i++)
    {
        DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
        if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T))))
        {
            T asType = (T)current;
            results.Add(asType);
        }
        FindChildren<T>(results, current);
    }
}

它基本上以遞歸方式獲取當前項目的子項,並將與請求的類型匹配的任何項目添加到提供的列表中。

然后,您只需要在頁面/按鈕處理程序/ ...中的某處執行以下操作:

var allTextBoxes    = new List<TextBox>();
FindChildren(allTextBoxes, this);

foreach(var t in allTextBoxes)
{
    t.Text = "Updated!";
}

簡單的方法就是TextBox.Text = String.Empty; 對於View中的每個TextBox。

您可以使用下面的代碼來找到控件。

 public static T FindChild<T>(DependencyObject depObj, string childName)
       where T : DependencyObject
    {
        // Confirm parent and childName are valid. 
        if (depObj == null) return null;

        // success case
        if (depObj is T && ((FrameworkElement)depObj).Name == childName)
            return depObj as T;

        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

            //DFS
            T obj = FindChild<T>(child, childName);

            if (obj != null)
                return obj;
        }

        return null;
    }

並可以清除文本框。

  TextBox txtBox1= FindChild<TextBox>(this, "txtBox1");
        if (txtBox1!= null)
            txtBox1.Text= String.Empty;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM