情况:
问题:
这是app.xaml.cs的代码
private static MedicineModel viewModel = null;
public static MedicineModel ViewModel {
get
{
if (viewModel==null)
{
viewModel = new MedicineModel();
viewModel.LoadData();
}
return viewModel;
}
}
MedicineModel.cs的代码是
namespace MedicinePlus.ViewModels
{
public delegate void EventDelegate();
public class MedicineModel
{
public List<MedicineData> Problems { get; set; }
public MedicineModel()
{
this.Problems = new List<MedicineData>();
}
public bool IsDataLoaded { get; set; }
public event EventDelegate Event1;
public void LoadData()
{
//place rt time Data here
IsDataLoaded = true;
this.Problems.Add(new MedicineData() { ID = 0, ProblemName = "Fever"});
this.Problems.Add(new MedicineData(){ID=1,ProblemName="Diarrhea"});
this.Problems.Add(new MedicineData() { ID=2,ProblemName = "sprain"});
this.Problems.Add(new MedicineData() { ID = 3, ProblemName = "bruise" });
OnEvent1();
}
protected virtual void OnEvent1()
{
EventDelegate handler = Event1;
if (handler!=null)
{
handler();
}
}
}
}
和MainPage.xaml.cs的代码是
其中textListViewSource是集合视图源的名称,listBoxTextItems是listBox的名称
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
App.ViewModel.Event1 += new EventDelegate(eventHandler);
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void eventHandler()
{
textListViewSource.Source = App.ViewModel.Problems;
listBoxTextItems.DataContext = App.ViewModel.Problems;
}
答案 0 :(得分:3)
让我们看看你的应用的工作流程:
App.ViewModel
属性,以检索视图模型并将其分配给您的datacontext App.ViewModel
属性的getter中,实例化viewmodel,并调用LoadData
方法LoadData
方法中,您(显然)加载数据,然后提升Event1
事件Event1
活动按照这些步骤,Event1
事件无法在MainPage
中引发,因为您在>>之后订阅了。
答案 1 :(得分:-1)
我已在此处上传了工作测试项目 - http://1drv.ms/NOvNSd。它是一个基于您的类的WPF项目,但您可以轻松地从中获取代码并将其放入Windows Phone项目中。