WinUI3: How to search and get control from loaded XAML file

Minh Van 171 Reputation points
2022-12-19T07:38:20.913+00:00

Hi,
In App.xaml.cs, I already loaded MainWindow.xaml from a persistent storage, such as 'C:\Projects\SamplePages\MainWindows.xaml' by using this codes:
271963-image.png

My question is that: How can I find and get the NavigationView control from this window? Thank you.
271986-image.png

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
889 questions
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,276 Reputation points
    2022-12-19T08:11:22.87+00:00

    With VisualTreeHelper
    I use utility functions like :

        private DependencyObject FindChildElementByName(DependencyObject tree, string sName)  
        {  
            for (int i = 0; i < Microsoft.UI.Xaml.Media.VisualTreeHelper.GetChildrenCount(tree); i++)  
            {  
                DependencyObject child = Microsoft.UI.Xaml.Media.VisualTreeHelper.GetChild(tree, i);  
                if (child != null && ((FrameworkElement)child).Name == sName)  
                    return child;  
                else  
                {  
                    DependencyObject childInSubtree = FindChildElementByName(child, sName);  
                    if (childInSubtree != null)  
                        return childInSubtree;  
                }  
            }  
            return null;  
        }  
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.