从 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);
}
}
}