How to bind Windows 8 XAML to a View Model. Although this post is based on an example using MVVM Cross, it will work for any MVVM framework, or even a customised one.
The Problem
I have a collection of data that I want to display in a customised format. My architecture is MVVM (using MVVM Cross).
Architecture
The principle here is that my data is stored in a model, but shaped in the ViewModel into a digestible format for the view. In my specific example, I have a list of people, and based on a specific criteria, I want to display a selection of these people in the view. For the sake of this article, I want to display people with a name starting with “D”.
Implementation
My model looks something like this:
public class Person
{
#region Basic attributes
public string Name { get; set; }
When my ViewModel is shown, I override an initialise method. Whilst this is not part of MVVM Cross per-se, it is basically a call to a custom initialise from the default `Init`:
private IEnumerable \_people;
public IEnumerable People
{
get { return \_people; }
set
{
\_people = value;
RaisePropertyChanged(() => People);
}
}
// Override custom init method
protected override void RealInit(NavigationParameter parameter)
{
var population = Mvx.Resolve();
People = population.Where(p => p.Name.StartsWith("D"));
}
So, my ViewModel now contains the correct, shaped data, I can just bind this:
…
And that should work.