Find all controls in WPF Window by type

后端 未结 17 1234
春和景丽
春和景丽 2020-11-21 10:14

I\'m looking for a way to find all controls on Window by their type,

for example: find all TextBoxes, find all controls implementing specific i

17条回答
  •  渐次进展
    2020-11-21 10:43

    My version for C++/CLI

    template < class T, class U >
    bool Isinst(U u) 
    {
        return dynamic_cast< T >(u) != nullptr;
    }
    
    template 
        T FindVisualChildByType(Windows::UI::Xaml::DependencyObject^ element, Platform::String^ name)
        {
            if (Isinst(element) && dynamic_cast(element)->Name == name)
            {
                return dynamic_cast(element);
            }
            int childcount = Windows::UI::Xaml::Media::VisualTreeHelper::GetChildrenCount(element);
            for (int i = 0; i < childcount; ++i)
            {
                auto childElement = FindVisualChildByType(Windows::UI::Xaml::Media::VisualTreeHelper::GetChild(element, i), name);
                if (childElement != nullptr)
                {
                    return childElement;
                }
            }
            return nullptr;
        };
    

提交回复
热议问题