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

本文关键字:GoBackCommand 参数 应用程序 Windows 应用 | 更新日期: 2023-09-27 18:19:31

在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();
}

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

这里有一个解决方案,尽管可能有更好的方法来完成

C#代码隐藏

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

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

然后在您的页面构造函数中,只需将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);
}

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

<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}"/>