如何在Windows应用商店应用中通过GoBackCommand传递参数

时间:2014-08-26 13:49:16

标签: c# xaml windows-store-apps

我想在NavigationHelper中使用Binding GoBackCommand时将参数传递给我访问的上一页。

XAML中的“后退”按钮

<Button x:Name="backButton"
                    Margin="39,59,39,0"
                    Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
                    Style="{StaticResource NavigationBackButtonNormalStyle}"
                    VerticalAlignment="Top"
                    AutomationProperties.Name="Back"
                    AutomationProperties.AutomationId="BackButton"
                    AutomationProperties.ItemType="Navigation Button"
                    IsEnabled="{Binding IsBackEnabled}"/>

我想传递类似于触发EventHandler并向前导航的参数,例如

C#代码背后

发送参数

private void Button_Click(object sender, RoutedEventArgs e)
{
    string myArg = "Hello";
    this.Frame.Navigate(typeof(AnotherPage), myArg);
}

并检索它

protected override void OnNavigatedTo(NavigationEventArgs e)
{
     string myParam = e.Parameter.ToString();
}

2 个答案:

答案 0 :(得分:1)

这是一个解决方案,虽然可能有更好的方法来做到这一点

C#代码背后

在使用GoBackCommand的页面中,声明一个GoBack方法:

private void GoBack()
{
    string myArg = "Hello";
    this.Frame.Navigate(typeof(AnotherPage), myArg);
}

然后在你的Page构造函数中,只需将GoBackCommand设置为GoBack方法:

public MyPage()
{
     this.InitializeComponent();
     this.navigationHelper = new NavigationHelper(this);
     this.navigationHelper.LoadState += navigationHelper_LoadState;
     this.navigationHelper.SaveState += navigationHelper_SaveState;
     this.navigationHelper.GoBackCommand = new RelayCommand(GoBack);
}

答案 1 :(得分:0)

您可以在CommandParameter中使用XAML来执行此操作。

<Button x:Name="backButton"
                    Margin="39,59,39,0"
                    Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
                    CommandParameter="This is my parameter"
                    Style="{StaticResource NavigationBackButtonNormalStyle}"
                    VerticalAlignment="Top"
                    AutomationProperties.Name="Back"
                    AutomationProperties.AutomationId="BackButton"
                    AutomationProperties.ItemType="Navigation Button"
                    IsEnabled="{Binding IsBackEnabled}"/>