0

从 UserControl 内部,我试图在其父级上引用一个方法。

public partial class Tab3_2Data : UserControl
{   
    public Tab3_2Data()
    {
        InitializeComponent();

        //MainPage mp = this.Ancestors().OfType<MainPage>().FirstOrDefault();
        //var x = VisualTreeHelper.GetParent(this);
        //var z = this.Parent;
        //var parent = this.Ancestors().Take(1).FirstOrDefault();
        // None of the above work.. all come back as null

        // Trying to access this method on the parent
        //ShowMessage("test", OperationStatus.Green);

试过这个还没有

    // only available OOB
    //mainPage = System.Windows.Application.Current.RootVisual as MainPage;

UserControl 被称为:

 <!-- Tab 3_2 -->
 <controls:TabItem Header="Groups and Roles">
     <UserControls:Tab3_2Data />
 </controls:TabItem>

EDIT2:这就是我的工作方式:

在用户控件中:

UserControl x:Class="xyz.ClientApp.UserControls.Tab3_2Data" Loaded="Tab3_2Data_OnLoaded"

然后在后面的代码中:

private void Tab3_2Data_OnLoaded(object sender, RoutedEventArgs e)
        {
            mp = this.Ancestors().OfType<MainPage>().FirstOrDefault();
            //mp.ShowMessage("test", OperationStatus.Green);
        }

它使用上面链接中引用的 VisualTreeEnumeration 帮助器类。

 public static class VisualTreeEnumeration
    {
        public static IEnumerable<DependencyObject> Descendents(this DependencyObject root, int depth)
        {
            int count = VisualTreeHelper.GetChildrenCount(root);
            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(root, i);
                yield return child;
                if (depth > 0)
                {
                    foreach (var descendent in Descendents(child, --depth))
                        yield return descendent;
                }
            }
        }

        public static IEnumerable<DependencyObject> Descendents(this DependencyObject root)
        {
            return Descendents(root, Int32.MaxValue);
        }

        public static IEnumerable<DependencyObject> Ancestors(this DependencyObject root)
        {
            DependencyObject current = VisualTreeHelper.GetParent(root);
            while (current != null)
            {
                yield return current;
                current = VisualTreeHelper.GetParent(current);
            }
        }
    }
4

1 回答 1

0

我相信只有在加载控件时父级才可用。您可以尝试在 UserControl.Loaded 事件的处理程序中运行此逻辑。此外,由于控件是 TabItem 的子控件,因此只有在 TabItem 可见时才会加载它。

于 2012-12-05T17:26:34.757 回答