mishan
mishan

Reputation: 1217

XAML Databinding singleton-like MVVM object

NOTES

I'm a rookie, I sometimes get stuck at simple and/or stupid thinks, this being one of them.

I get the general idea of databinding, I've got through some of the tutorials on the net and googled for a few hours through lots and lots of text, which only made me slightly confused.

PROBLEM

I'm working on Windows Phone 8 C#/XAML .NET 4.5 Application.

Using a webservice provided to me with a few methods I'm loading data that I need to view (sometimes in different combinations) and I need to store most of them for the time the app is running.

QUESTIONS

  1. How to achieve this?

  2. If I'd like to set an itemSource of a listBox/longListSelector or Text of the textBox to value in for example PersonalInfoModel inside the MainViewModel, how should i do it?

P.S.: As is written in the note at the start of the question, I'm a rookie. I know that it's hard with us sometimes, but none of the great thinkers just spawned from the great void, thats why I'm asking for a more detailed explanation then just "You shlould set your object as datasource in the window and then set this".

Upvotes: 2

Views: 1952

Answers (1)

Marc
Marc

Reputation: 13194

The question you're asking is, basically: How do I connect View and ViewModel? I totally agree that this is the most confusing problem to solve when you're getting started with MVVM and that this question is completely ignored by many tutorials and posts on MVVM.

The answer is: There are many ways to get the ViewModel where you want it to be, that is in the View's DataContext. Though you could do it purely in XAML, Microsoft suggests to set the DataContext like this, as far as I can recall the WP project templates:

In your Views constructor in codebehind, simply call:

DataContext = App.MainViewModel;

One of the most valuable sources that helped me get this problem straight is this post in

Paul Stovell's Blog

It's about WPF and not WP8 but it should help nonetheless.

To perform the actual binding, you can now follow the tutorials, for example:

<TextBlock Text="{Binding PersonalInfoModel.Name}" />

Upvotes: 4

Related Questions