简体   繁体   中英

How to call LoadData() from MainPage.xaml.cs

Situation:

  • i have a main page xaml whose data context is set to MainVieweModelSampleData.xaml
  • i have a MainViewModel class that contains a collection named “Problems” of type ItemViewModel class
  • i have a LoadData function in MainviewModel class where ItemViewModel class is instantiated and instances are added to Problems collection

Question:

How do i call it from MainPage.xaml.cs currently i am calling it from app.xaml.cs using below code :

    private static MainViewModel viewModel;

    public static MainViewModel ViewModel
    {

        get
        {
            if (viewModel==null)
            {
                viewModel = new MainViewModel();
                viewModel.LoadData();
            }
            return viewModel;
        }

    }

In your App.Xaml.cs, You should define your ViewModel as below,

private static MainViewModel _viewModel;

public static MainViewModel ViewModel
{
    get { return _viewModel ?? (_viewModel = new MainViewModel()); }
}

Then in your MainPage , you call the 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM