情况:
问题:
如何从MainPage.xaml.cs中调用它,目前我使用以下代码从app.xaml.cs调用它:
private static MainViewModel viewModel;
public static MainViewModel ViewModel
{
get
{
if (viewModel==null)
{
viewModel = new MainViewModel();
viewModel.LoadData();
}
return viewModel;
}
}
答案 0 :(得分:2)
在App.Xaml.cs中,您应该如下定义ViewModel,
private static MainViewModel _viewModel;
public static MainViewModel ViewModel
{
get { return _viewModel ?? (_viewModel = new MainViewModel()); }
}
然后在您的MainPage中调用viewModel,
public MainPage()
{
InitializeComponent();
//Here you set the ViewModel
this.DataContext = App.ViewModel;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//Here you load the data
App.ViewModel.LoadData();
}