如何在 wp 8.1 中使用 mvvm 在导航页面之间传递数据?

How to pass data between pages on navigation using mvvvm in wp 8.1?

我是 windows phone 8.1 的新手。我有一个视图列表,当用户单击一个项目时,他应该移动到该项目的项目详细信息页面,结果在视图模型中我绑定了一个执行以下操作的命令:

 ((Frame)Window.Current.Content).Navigate(typeof(ItemView), item);

到目前为止一切正常。但是如何在项目详细信息页面的视图模型中接收项目对象呢?

我可以在后面的代码中访问它,但是针对该问题的 mvvm 最佳实践是什么。

假设您有以下列表。我省略了项目模板和项目源的声明:

<ListView IsItemClickEnabled="True" x:Name="lvItems">
    <Interactivity:Interaction.Behaviors>
        <Core:EventTriggerBehavior EventName="ItemClick">
            <Core:InvokeCommandAction Command="{Binding NavigateDetailsCommand, Mode=OneWay}" InputConverter="{StaticResource ItemClickConverter}" CommandParameter="{Binding SelectedItem, ElementName=lvItems}"/>
        </Core:EventTriggerBehavior>
    </Interactivity:Interaction.Behaviors>
</ListView>

然后您需要一个转换器,将点击事件转换为实际项目:

public class ItemClickConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var icea = (ItemClickEventArgs)value;
        if (icea != null)
            return icea.ClickedItem;
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

最后一件事是将所有内容传递给命令的视图模型:

public RelayCommand<MyEntity> NavigateDetailsCommand;

// In your constructor, do this:
this.NavigateDetailsCommand= new RelayCommand<MyEntity>(navigateDetails);
// I'm assuming you injected a navigation service into your viewmodel..
this._navigationService.Configure("itemviewpage", typeof(ItemView));


// Declare a method that does the navigation:
private void navigateDetails(MyEntity item) {
    this._navigationService.NavigateTo("itemviewpage", item);
}