可以知道我的UserControl在哪里

时间:2014-05-01 15:39:34

标签: c# user-controls windows-runtime winrt-xaml

假设我有一个UserControl,我在不同的页面中使用它。

从我的userControl的代码后面,是否可以动态地知道它在哪个页面?

MyUserControl.xaml

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

第1页

        <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

2 个答案:

答案 0 :(得分:1)

假设您可以访问实际控制对象,则可以垂直遍历可视树。或者,您可以使用WinRTXamlToolkit中包含的扩展名来执行mycontrol.GetAncestors<Page>()

之类的操作

EDIT *(Filip Skakun)

如果您不想/需要完整的工具包 - 您可以使用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);
        }
    }
}

答案 1 :(得分:0)

在典型情况下,Page位于视觉树根部的Frame中,因此您也可以从根部开始抓取它:

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.
}