可以知道我的UserControl在哪里

本文关键字:UserControl 在哪里 我的 | 更新日期: 2023-09-27 18:01:15

假设我有一个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>

第2页

    <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

可以知道我的UserControl在哪里

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

编辑*(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);
        }
    }
}

在典型情况下,您的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.
}