class - 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 调用,并返回要在第二页的集合视图中显示的图像列表。
在这个服务类中,我需要访问上面传递的两个变量 (photograperCode
和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();
}
}
}
我试过这样
((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>
解决方案
这应该可以正常工作。首先在你的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();
}
}
推荐阅读
- javascript - Proxyquire 显示错误“找不到模块”
- swift - 如何从 Firestore 获取数组字段并在 Swift 中写入 struct 字段?
- windows - 如何使用 nuget.exe 从 artifactory 下载受保护的(私有)nuget 包
- javascript - 如何绘制像两个或多个表通过 D3.js 中的公共值连接的图形?
- r - 如何使系列静止
- java - 为什么返回值对象在 URLClassPath 的 getResources 函数中有两个额外的字段?
- django - 从 prepare_field 返回字典
- git - Sublime Text 3.2 中的 GIT 集成仍然出现
- hadoop - 无法写入 HDFS:WARN hdfs.DataStreamer - Unexpected EOF
- django - 如何在friends_list/followers_list中显示不同的头像,我正在练习django