如何将参数从一个页面传输到另一页



我使用template10的UWP。我想拥有一个带有项目的网格,并且在我想打开另一个页面的项目的OnClick事件中。通常的

var item = (Invitation)e.ClickedItem;
this.Frame.Navigate(typeof(MainPage), item.Id);

似乎不起作用。我该怎么做?

我做了一个简单的示例,以演示如何将参数从一个页面传递到另一页。我不会使用MVVM架构,因为这将是一个简单的演示。

这是我的主页:

<Page
    x:Class="App1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="using:App1"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Name="mainWindow"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListView
            Name="lvDummyData"
            IsItemClickEnabled="True"
            ItemClick="lvDummyData_ItemClick"
            ItemsSource="{Binding ElementName=mainWindow, Path=DummyData}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Page>

您可以看到这里没有什么特别的。只有单击启用的ListView。

这是背后的代码:

public ObservableCollection<string> DummyData { get; set; }
public MainPage()
{
    List<string> dummyData = new List<string>();
    dummyData.Add("test item 1");
    dummyData.Add("test item 2");
    dummyData.Add("test item 3");
    dummyData.Add("test item 4");
    dummyData.Add("test item 5");
    dummyData.Add("test item 6");
    DummyData = new ObservableCollection<string>(dummyData);
    this.InitializeComponent();
}
private void lvDummyData_ItemClick(object sender, ItemClickEventArgs e)
{
    var selectedData = e.ClickedItem;
    this.Frame.Navigate(typeof(SidePage), selectedData);
}

在这里,我有一个可观察到的集合,我正在填充虚拟数据。除此之外,我还有从列表视图中单击事件,然后将参数传递到我的SideView页面。

这是我的侧视页面的外观:

<Page
    x:Class="App1.SidePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    x:Name="sidePage"
    mc:Ignorable="d">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Name="txtResultDisplay" />
    </Grid>
</Page>

这就是我背后的代码的样子:

public SidePage()
{
    this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    string selectedDummyData = e.Parameter as string;
    if (selectedDummyData != null)
    {
        txtResultDisplay.Text = selectedDummyData;
    }
    base.OnNavigatedTo(e);
}

在这里,我们有一个OnNavigatedTo事件,我们可以通过该事件传递参数。这是您缺少的部分,因此请注意。希望这有助于解决您的问题。

最新更新