One ViewModel and Several Views

I have some questions about Windows Phone 8 and the MVVM template.

  • I am wondering how I can bind elements from many displayed pages to one ViewModel (there is only one ViewModel because I want to use a facade template).

  • Every tutorial I've seen contains code in which ViewModel and Model are in static fields. I am not sure of the correctness of this. Can someone tell me where in the WP8 application you need to create a new model and ViewModel to do it right? (By “correct,” I also mean that I can link elements from several pages to this ViewModel.) I have been looking at the App.xaml.cs file, but still not sure.

Thank you for your help!

+4
source share
2 answers

I have recently been worried about such issues. In the end, I used App.xaml.csto create the viewmodel.

The answers

Yes, this is the right way to create a static viewmodel in App.xaml.cs, because the class Appis accessible from any page of the application, it is also correct to declare them static, because you want to access it without creating an instance of the application, and, as Tarik said in your answer:

ViewModel and Model are static fields, so values ​​are not destroyed if they go beyond. It also makes it easy to refresh multiple pages.

: , , , .

App.xaml.cs RootFrame:

private static MainViewModel viewModel; //not sure how your viewmodel class is named
public static MainViewModel ViewModel   //and a property to access it from
{
  get
  {
    if(viewModel == null)               //which creates the viewModel just before
       viewModel = new MainViewModel(); //it first used
    return viewModel;
  }
}

- , jst ( InitializeComponents();):

DataContext = App.ViewModel;

a >

, OnNavigatedTo() ( , ), , ViewModel, ).

:

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);             //not needed, base method is empty and does nothing
        DataContext = null;                //important part, whenever you navigate, refreshes the ViewModel - no deletion, just resetting of the DataContext, so the page won't get stuck
        DataContext = App.ViewModel;      //and finally the resetting
    }

, :

  • , , backbrowsing - , , . , , "".

, .

, , , :

  • , , OnNavigatedTo().

  • It

(, , get:))

xaml :

<TextBlock text="{Binding SomePropertyNameFromViewModel}" />

<TextBlock text="{Binding SomeModelInViewModel.ItsProperty}" />

, :

<ListBox IemSource="{Binding SomeCollectionInViewModel}">
...rest omitted for brevity...

et cetera...

? , . ViewModel 6 7 , , , , .

P.S.: , , , WP pivot .

, App.xaml.cs, , . .

+9

, :

, App.xaml.cs ViewModel . ViewModel . !

ViewModel Model , , . .

+1

All Articles