[英]Xamarin - How to pass variable to viewmodel
我有 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 調用,並返回要在第二個頁面的集合視圖中顯示的圖像列表。
在這個服務類中,我需要訪問上面傳遞的兩個變量( 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 為空,但在 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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.