ArghArgh
ArghArgh

Reputation: 373

Is possible to know where my UserControl is

Suppose that I have a UserControl, and I use it in different pages.

From the codebehind my userControl, is it possible to know dynamically which pages it is in?

MyUserControl.xaml

    <UserContol bla bla bla
            bla bla bla
            x:Name=ucbox>
        other xml stuffs
    </UserContol>

Page1

        <Page x:Class="Page1"
             xmlns:local=using:"path of userContol">

             <local:myuserControl     />
        </Page>

Page2

    <Page x:Class="Page2"
         xmlns:local=using:"path of userContol">

           <local:myuserControl     />
    </Page>

MyUserControl.xaml.cs

//how can i do that?
var p = get the root of the Page1 or 2

Upvotes: 0

Views: 140

Answers (2)

Filip Skakun
Filip Skakun

Reputation: 31724

In typical situations your Page is in a Frame that is at the root of the visual tree, so you can also grab it starting at the root this way:

var frame = Window.Current.Content as Frame;

if (frame != null)
{
    var page = frame.Content as Page;

    if (page != null)
    {
        // you have found you page!
    }
    else
    {
        // the frame has not loaded a page yet - this isn't very likely to happen
    }
}
else
{
    // the app is either not initialized yet
    // or you have modified the default template and Frame is not at the root.
}

Upvotes: 0

Nate Diamond
Nate Diamond

Reputation: 5575

Assuming you have access to the actual control object, you can vertically traverse the visual tree. Or, you can use the extensions included in the WinRTXamlToolkit to do something like mycontrol.GetAncestors<Page>().

EDIT* (Filip Skakun)

If you don't want/need the full toolkit - you can just use this bit of the VisualTreeHelperExtensions:

public static class VisualTreeHelperExtensions
{
    public static IEnumerable<T> GetAncestorsOfType<T>(this DependencyObject start) where T : DependencyObject
    {
        return start.GetAncestors().OfType<T>();
    }

    public static IEnumerable<DependencyObject> GetAncestors(this DependencyObject start)
    {
        var parent = VisualTreeHelper.GetParent(start);

        while (parent != null)
        {
            yield return parent;
            parent = VisualTreeHelper.GetParent(parent);
        }
    }
}

Upvotes: 1

Related Questions