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<Person> _people; public IEnumerable<Person> People { get { return _people; } set { _people = value; RaisePropertyChanged(() => People); } } // Override custom init method protected override void RealInit(NavigationParameter parameter) { var population = Mvx.Resolve<Population>(); People = population.Where(p => p.Name.StartsWith("D")); }
So, my ViewModel now contains the correct, shaped data, I can just bind this:
<Page.Resources> <DataTemplate x:Name="PeopleTemplate"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Name}"/> </StackPanel> </DataTemplate> </Page.Resources> … <ListView x:Name="ItemListView" ItemsSource="{Binding People}" Width="Auto" Height="Auto" ItemTemplate="{StaticResource PeopleTemplate}" ShowsScrollingPlaceholders="False" />
And that should work.
Reblogged this on Dinesh Ram Kali..