Class Xamarin-如何将变量传递给viewmodel

Class Xamarin-如何将变量传递给viewmodel,class,variables,xamarin,Class,Variables,Xamarin,我有两种观点。其中一个有一个事件,它将两个变量传递到第二个页面并向上加载该页面: private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e) { var item = (GalleryListEntry)e.CurrentSelection.FirstOrDefault(); Navigation.PushModalAsync(new Ga

我有两种观点。其中一个有一个事件,它将两个变量传递到第二个页面并向上加载该页面:

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();
    }
第二个页面有一个集合视图,它有自己的Bindingsource。 对于这个bindingsource,我有一个模型、一个服务和一个ViewModel。该服务由Viewmodel调用,并返回要在第二个页面的集合视图中显示的图像列表

在这个服务类中,我需要访问上面传递的两个变量(
photographercode
galleryCode
),但我不知道如何将变量传递给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();
        }
    }
}
但是我得到了这个错误:
System.NullReferenceException:“对象引用未设置为对象的实例。”
BindingContext为Null,但在Xaml文件中我有以下内容:

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

这应该可以正常工作。首先在您的
库中

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();
  }
}
class GalleryViewModel
{
公共可观测集合库{get;set;}
公共GalleryViewModel(字符串pCode、字符串gCode)
{
this.pCode=pCode;
this.gCode=gCode;
Galleries=new GalleryService().GetImageList();
}
}

谢谢,但是现在当我有一个错误时,我的gallery.xaml中出现了一个错误。错误如下:
严重性代码描述项目文件行抑制状态错误XLS0507类型“GalleryViewModel”不能用作对象元素,因为它不是公共的,或者没有定义公共无参数构造函数或类型转换器。GalShare Gallery.xaml 10
删除您不需要的行。我们已经有了将GalleryViewModel绑定到代码隐藏中的视图
class GalleryViewModel
{
  public ObservableCollection<Gallery> Galleries { get; set; }
  public GalleryViewModel(string pCode, string gCode)
  {
    this.pCode = pCode;
    this.gCode = gCode;
    Galleries = new GalleryService().GetImageList();
  }
}