将数据参数从模型传递到下一页Prism Xamarin Forms

时间:2018-11-28 13:29:58

标签: c# xamarin xamarin.forms prism

我需要使用Prism将数据从ViewModel 1传递到ViewModel 2。

TodoItem是我的模型,带有以下字符串:

public TodoItem _todotItem { get; set; }

private readonly INavigationService _navigationService;

我在构造函数中分配了它:

public MainPageViewModel(INavigationService navigationService, TodoItem todotItem)
{
    _navigationService = navigationService;
    _todotItem = todotItem;
}

这是我用来导航到下一页的代码(包括参数):

NavigationParameters navParams = new NavigationParameters();
navParams.Add("PassedValue", _todoItem.name);

_navigationService.NavigateAsync("SecondPage", navParams);

当我在_todoItem.name上设置断点时,它会显示 null 。在我单击listview之前已获取数据。我想念什么?

编辑:

这就是我的导航方式(从listview单击):

private EventItem _selectedEvent { get; set; }
public EventItem SelectedEvent
{
    get { return _selectedEvent; }  
    set
    {
        if (_selectedEvent != value)
        {
            if (Device.RuntimePlatform == Device.iOS)
            {
                _selectedEvent = null;
            }
            else
            {
                _selectedEvent = value;
            }
            NavigationParameters navParams = new NavigationParameters();

            navParams.Add("PassedValue", _todoItem.name);


            _navigationService.NavigateAsync("SecondPage", navParams);
        }
    }
}

我确实使用了正确的方法来捕获第二个ViewModel上的参数(但是,我在第一个ViewModel中得到了 null ):

public void OnNavigatingTo(INavigationParameters parameters)
{
    if (parameters.ContainsKey("PassedValue"))
    {
        _todo = (string)parameters["PassedValue"];

        OnPropertyChanged("Todo");
    }

}

我使用HTTPClient来获取数据。

1 个答案:

答案 0 :(得分:0)

为了捕获第二页上的参数,必须使用Prism.Navigation.INavigationAware。请检查下面的代码,也许会对您有所帮助。

./ Views / ItemView.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms" 
    prism:ViewModelLocator.AutowireViewModel="True" 
    x:Class="Project.Views.ItemView"
    Title="{Binding Title}">

    <StackLayout>
        <!-- List View -->
        <ListView ItemsSource="{Binding Items}" 
                  CachingStrategy="RecycleElement" 
                  HorizontalOptions="FillAndExpand"
                  VerticalOptions="FillAndExpand" 
                  HasUnevenRows="True" 
                  SelectionMode="None">
            <ListView.Behaviors>
                <b:EventToCommandBehavior EventName="ItemTapped" 
                                          Command="{Binding ItemTappedCommand}" 
                                          EventArgsParameterPath="Item" />
            </ListView.Behaviors>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <!-- Data Template Cell -->
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

</ContentPage>

./ ViewModels / ViewModelBase.cs

using Prism;
using Prism.Mvvm;
using Prism.Navigation;
using System;

namespace Project.ViewModels
{
    // INavigationAware provides a way for objects involved in navigation to be notified of navigation activities.
    public class ViewModelBase : BindableBase, INavigationAware, IDestructible
    {
        // ...

        protected INavigationService NavigationService { get; private set; }

        public ViewModelBase(INavigationService navigationService) => NavigationService = navigationService;

        /// <summary>
        /// Called when the implementer is being navigated away from.
        /// </summary>
        public virtual void OnNavigatedFrom(INavigationParameters parameters)
        {

        }

        /// <summary>
        /// Called when the implementer has been navigated to.
        /// </summary>
        public virtual void OnNavigatedTo(INavigationParameters parameters)
        {

        }

        // ...
    }
}

./ ViewModels / ItemViewModel.cs

using Prism.Navigation;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;

namespace Project.ViewModels
{
    public class ItemViewModel : ViewModelBase
    {
        // ...

        private ObservableCollection<ItemList> _items;
        public ObservableCollection<ItemList> Items
        {
            get => _items;
            set => SetProperty(ref _items, value);
        }

        public ICommand ItemTappedCommand => new AsyncCommand(ItemTappedCommandAsync);

        public ItemViewModel(INavigationService navigationService)
            : base(navigationService)
        {
            Items = new ObservableCollection<ItemList>();
            // Load the data
        }

        // ...

        private async Task ItemTappedCommandAsync(object item)
        {
            var navParams = new NavigationParameters
            {
                { "ItemSelected", (Item)item }
            };

            await NavigationService.NavigateAsync(nameof(ItemDetailView), navParams);
        }
    }
}

./ ViewModels / ItemDetailViewModel.cs

using Prism.Navigation;
using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;

namespace Project.ViewModels
{
    public class ItemDetailViewModel : ViewModelBase
    {
        // ...

        public override void OnNavigatingTo(INavigationParameters parameters)
        {
            // Capture the parameter
            System.Diagnostics.Debug.WriteLine(parameters);
        }

        // ...
    }
}