2013-11-14 24 views
0

當在一個子控件中處理一個事件時,我需要在我的MainPage.xaml.cs類中調用一個方法。調用this.Parent不起作用,因爲它只返回在樹中的第DependencyObject的,我不能從那個如何獲取父容器,例如Windows Phone中的PhoneApplicationPage?

我在PhoneApplicationPage以下佈局PhoneApplicationPage

<Grid x:Name="LayoutRoot" Background="Transparent"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="AUTO"/> 
     <RowDefinition Height="*"/> 
     <RowDefinition Height="AUTO"/> 
    </Grid.RowDefinitions> 

    <Grid Height="85" VerticalAlignment="Top" Grid.Row="0"></Grid> 

    <Grid Grid.Row="1" Name="gridContent" /> 

    <ug:UniformGrid Rows="1" Columns="5" Height="85" VerticalAlignment="Bottom" Grid.Row="2"> 
     <tabs:TabItem Name="tabOverview" TabItemText="OVERVIEW" TabItemImage="overview_64.png" /> 
     <tabs:TabItem Name="tabLogs" TabItemText="LOGS" TabItemImage="log_64.png"/>   
    </ug:UniformGrid> 
</Grid> 

與下面的代碼:

public partial class MainPage : PhoneApplicationPage 
{ 
    public MainPage() 
    { 
     InitializeComponent(); 

     gridContent.Children.Add(new OverviewUserControl()); 
    } 

    public void UpdateContent(UserControl control) 
    { 
     // I need to call this method from the TabItem Tap event 
     gridContent.Children.Clear(); 
     gridContent.Children.Add(control); 
    } 
} 

當自來水事件發生時,我需要什麼對應於用戶的自來水,以取代gridContent內容。這就是我如何處理點擊事件:

private void TabItem_Tap(object sender, System.Windows.Input.GestureEventArgs e) 
{ 

    // var parent = this.Parent; //<-- this doesn't get the PhoneApplicationPage 

    var ti = sender as TabItem; 
    if (ti != null) 
    { 
     string tab = ""; 
     switch (ti.Name) 
     { 
      case "tabOverview": 
       // I need a reference to MainPage here to call 
       // MainPage.UpdateContent(new LogsUserControl()) 
       break; 
      case "tabLogs": 
       // I need a reference to MainPage here to call 
       // MainPage.UpdateContent(new OverviewUserControl()) 
       break; 
     } 

    } 
} 

問題

所以,問題是我怎麼能叫從TabItem_TapMainPage的方法?

回答

2

這做到了:

var currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as MainPage; 

用法:

private void TabItem_Tap(object sender, System.Windows.Input.GestureEventArgs e) 
{ 
    var currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as MainPage; 

    if (ti != null) 
    { 
     switch (ti.Name) 
     { 
      case "tabOverview": 
       currentPage.UpdateContent(new OverviewUserControl()); 
       break; 
      case "tabLogs": 
       currentPage.UpdateContent(new LogsUserControl()); 
       break; 
     } 
    } 
} 
相關問題