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

时间:2015-02-15 07:59:19

标签: c# mvvm windows-phone-8.1 mvvm-light

我是Windows Phone 8.1的新手。我有一个视图列表,当用户点击某个项目时,他应该移动到该项目的项目详细信息页面,因此在视图模型中我绑定了一个执行以下命令的命令:

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

直到现在每件事都运转良好。但是如何在项目详细信息页面的视图模型中接收项目对象?

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

1 个答案:

答案 0 :(得分:0)

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

<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>

然后你需要一个将click事件转换为实际项目的转换器:

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

最后一件事是viewmodel,你将所有内容传递给命令:

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