首页 > 解决方案 > Xamarin - 如何将变量传递给视图模型

问题描述

我有 2 个视图。一个有一个事件,它将两个变量传递给第二个页面并加载页面:

private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var item = (GalleryListEntry)e.CurrentSelection.FirstOrDefault();
        Navigation.PushModalAsync(new Gallery(item.PhotographerCode, item.GalleryCode));
    }

在第二页我有这个:

public Gallery(string photographerCode, string galleryCode)
    {
        InitializeComponent();
    }

第二个页面有一个 Collection 视图,它有自己的 Bindingsource。对于这个绑定源,我有一个模型、一个服务和一个 ViewModel。该服务由 Viewmodel 调用,并返回要在第二页的集合视图中显示的图像列表。

在这个服务类中,我需要访问上面传递的两个变量 (photograperCodegalleryCode),但我不知道如何将变量传递给 ViewModel,因此我可以将其转发给类。

视图模型:

using GalShare.Model;
using GalShare.Service;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace GalShare.ViewModel
{
    class GalleryViewModel
    {
        public ObservableCollection<Gallery> Galleries { get; set; }
        public GalleryViewModel()
        {
        Galleries = new GalleryService().GetImageList();
        }
    }
}

我试过这样

        ((GalleryViewModel)this.BindingContext).pCode = photographerCode;
        ((GalleryViewModel)this.BindingContext).gCode = galleryCode;

但我收到此错误:System.NullReferenceException: 'Object reference not set to an instance of an object.' BindingContext 为 Null,但在 Xaml 文件中我有这个:

<ContentPage.BindingContext>
    <vm:GalleryViewModel/>
</ContentPage.BindingContext>

标签: classvariablesxamarin

解决方案


这应该可以正常工作。首先在你的Gallery

public Gallery(string photographerCode, string galleryCode)
{
  InitializeComponent();
  BindingContext = new GalleryViewModel(photographerCode, galleryCode);
}

现在在 ViewModel

class GalleryViewModel
{
  public ObservableCollection<Gallery> Galleries { get; set; }
  public GalleryViewModel(string pCode, string gCode)
  {
    this.pCode = pCode;
    this.gCode = gCode;
    Galleries = new GalleryService().GetImageList();
  }
}

推荐阅读