簡體   English   中英

在UWP頁面中查找所有TextBox控件

[英]Find all TextBox controls in UWP Page

我需要找到UWP頁面上但沒有運氣的所有TextBox。 我認為這將是Page.Controls上的一個簡單的foreach,但這不存在。

使用DEBUG我可以看到,例如,一個網格。 但是我必須首先將Page.Content轉換為Grid才能看到Children集合。 我不想這樣做,因為它可能不是頁面根目錄中的網格。

先感謝您。

更新:這與'按類型查找WPF窗口中的所有控件'不同。 那是WPF。 這是UWP。 他們是不同的。

你快到了! 將Page.Content轉換為UIElementCollection,這樣您就可以獲得Children集合並且是通用的。

如果element是UIElement,那么你必須使你的方法遞歸並查找Content屬性,或者如果element是UIElementCollection,則查找子元素。

這是一個例子:

    void FindTextBoxex(object uiElement, IList<TextBox> foundOnes)
    {
        if (uiElement is TextBox)
        {
            foundOnes.Add((TextBox)uiElement);
        }
        else if (uiElement is Panel)
        {
            var uiElementAsCollection = (Panel)uiElement;
            foreach (var element in uiElementAsCollection.Children)
            {
                FindTextBoxex(element, foundOnes);
            }
        }
        else if (uiElement is UserControl)
        {
            var uiElementAsUserControl = (UserControl)uiElement;
            FindTextBoxex(uiElementAsUserControl.Content, foundOnes);
        }
        else if (uiElement is ContentControl)
        {
            var uiElementAsContentControl = (ContentControl)uiElement;
            FindTextBoxex(uiElementAsContentControl.Content, foundOnes);
        }
        else if (uiElement is Decorator)
        {
            var uiElementAsBorder = (Decorator)uiElement;
            FindTextBoxex(uiElementAsBorder.Child, foundOnes);
        }
    }

然后用以下方法調用該方法:

        var tb = new List<TextBox>();
        FindTextBoxex(this, tb);
        // now you got your textboxes in tb!

您還可以使用VisualTreeHelper文檔中的以下泛型方法來獲取給定類型的所有子控件:

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);

在我看來,你可以像在WPF中那樣做。 因為UWP大多使用與WPF相同的XAML。

所以,請查看有關WPF相同問題的答案

暫無
暫無

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

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