将数据传递给另一个ViewModel
问题描述:
你好,我想传递一个字符串到另一个viewmodel。我试图使用这段代码,但它不符合我的目的,因为我需要知道收件人视图的viewmodel中的字符串值。我怎样才能做到这一点?你也可以用mvvm-light和命令提出更好的方法,因为我的概念对于这两者来说并不那么清楚。将数据传递给另一个ViewModel
public MainViewModel()
{
GiveDetails = new RelayCommand<object>(DoSomething);
}
private void DoSomething(object param)
{
var rootFrame = (App.Current as App).RootFrame;
rootFrame.Navigate(new System.Uri("/Details.xaml?ID="+param.ToString(), System.UriKind.Relative));
}
我目前没有线索如何处理收件人viewmodel上的参数。
答
在Stack Careers Browser当从主页面视图中选择职业生涯时,我在DetailsPage.xaml.cs的OnNavigatedTo事件中具有以下内容。
if (DataContext == null)
{
string selectedIndex = "";
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
**int index = int.Parse(selectedIndex);**
**DataContext = _vm = new JobPostingViewModel(App.ViewModel.JobPostings[index]);**
Indicators.SetIndicators(this, DataContext);
await _vm.ScrapeThatScreenAsync(_vm.JobPosting.Id);
}
}
相应的视图模型有一个构造函数,看起来像这样:
public JobPostingViewModel(JobPosting jobPosting)
{
if (jobPosting == null)
throw new ArgumentNullException("jobPosting");
JoelTestResults = new ObservableCollection<JoelTestResult>();
// JoelTestResults = new ObservableCollection<string>(){"a","b","c"};
_jobPosting = jobPosting;
if (jobPosting.Categories != null && jobPosting.Categories.Any())
ProcessCategories(jobPosting.Categories);
}
哪里需要一些基本对象,以处理更多的信息,并在Windows Phone 8的方式显示出来。