在子控件中处理事件时,我需要调用 MainPage.xaml.cs 类中的方法。调用this.Parent
不起作用,因为它只返回树中的第一个 DependencyObject,而我无法从中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;
}
}
}
问题
所以问题是如何调用MainPage
from中的方法TabItem_Tap
?