2012-12-05 64 views
0

從UserControl內部我試圖在其父項上引用一個方法。從Silverlight中的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); 

試過this但沒有

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

用戶控件被稱爲像:

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

回答

0

我相信父母只有在控件加載時纔可用。您可以嘗試在UserControl.Loaded事件的處理程序中運行此邏輯。 另外,由於控件是TabItem的子項,只有在TabItem可見時纔會加載。