uwpframeuwp-xamlmulti-window

how to get pages or frames inside CoreWindow in UWP app


I am working on a UWP library , in which I would like get all frames or pages inside a CoreWindow or CoreApplicationView.

In multi window app,

I can get all available views by this code CoreApplication.Views . Views is a collection of CoreApplicationView .

From this all I want is to get is frames and pages loaded inside this each views.

Can anybody help me in this.

Thanks

Noorul.


Solution

  • CoreWindow or CoreApplicationView does not provide APIs to directly access internal Xaml elements.

    If you want to access the Xaml element in the window, you need to get the Window object. Currently, UWP application can only get the active window

    If you need to get the Xaml elements in the current window, you need to use Window.Current:

    public IEnumerable<Frame> GetFrames(Frame rootFrame = null)
    {
        if (rootFrame == null)
            rootFrame = Window.Current.Content as Frame;
        if (rootFrame.Content is Page page)
        {
            var children = VisualTreeFindAll<Frame>(page);
            if (children.Count > 0)
            {
                foreach (var childFrame in children)
                {
                    GetFrames(childFrame);
                    yield return childFrame;
                }
            }
        }
    }
    
    public IList<T> VisualTreeFindAll<T>(DependencyObject element)
        where T : DependencyObject
    {
        List<T> retValues = new List<T>();
        var childrenCount = VisualTreeHelper.GetChildrenCount(element);
        for (var i = 0; i < childrenCount; i++)
        {
            var child = VisualTreeHelper.GetChild(element, i);
            var type = child as T;
            if (type != null)
            {
                retValues.Add(type);
            }
            retValues.AddRange(VisualTreeFindAll<T>(child));
        }
        return retValues;
    }
    

    Usage

    var frames = GetFrames();