Howdy again.

As promised, i will make a short tutorial with exploration in a bit more complex app.( If you see this for the first time i strongly recommend that you read this post first, just to understand the basics of the mvvm light toolkit)

If all the things are clear, i will start now. I made an application that sounds like this : We have a zoo park, witch have animals.

Each animal have 2 properties (name and age). Now i want those animal properties to show up in a listbox on the phone, and when i select one of them, his name property to appear in a textBlock.

Easy, isn’t it?

Here are some prints with the app, just to show you that it’s working:

                                 

 

OK, so now that you trust me, let me show you how it’s made to work ;) .

I’m gonna start with the model. Remember from last post that the Model was empty, this time the model contains 2 classes,

Animal.cs and ZooPark.cs. I’m gonna show you how they look :

namespace MvvmLight1.Model
{
    public class Animal
    {

        private int age ;
        private string name = string.Empty;

        public int Age { get { return this.age; } set { this.age=value;} }
        public string Name { get { return this.name; } set { this.name=value;} }
    }
}

This is the basic property container class, so we have animal with 2 properties Age and Name.

The ZooPark.cs look like this:

namespace MvvmLight1.Model
{

    public class ZooPark
    {
        public ZooPark()
        {

            addAnimal(10, "cat");
            addAnimal(4, "dog");

        }

        private ObservableCollection<Animal> zPark = new ObservableCollection<Animal>();

        public ObservableCollection<Animal> zooPark
        {
            get
            {
                return this.zPark;
            }

            set
            {
                this.zPark = value;
            }
        }

        private void addAnimal(int age,string name)
        {
            Animal animal = new Animal();

            animal.Name = name;
            animal.Age = age;
            zPark.Add(animal);

        }
    }
}

So basically this class declares an ObservableCollection of type Animal and it populates it with a dog and a cat.  It also declares a property of the same type, witch we will be using to interact with the collection.

Now that we are ok with the model  let’s move to MainViewModel.cs , witch will make the binding between the View  and the Model.

The class looks like this:

namespace MvvmLight1.ViewModel
{

    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {

        }

        private Animal selectedAnimal = null;
        public Animal SelectedAnimal
        {
            get
            {
                return this.selectedAnimal;
            }
            set
            {
                this.selectedAnimal = value;
                RaisePropertyChanged("SelectedAnimal");
            }
        }

        private ZooPark zoo = new ZooPark();
        public ZooPark Zoo
        {
            get
            {
                return this.zoo;
            }
            set
            {
                this.zoo = value;
                RaisePropertyChanged("Zoo");
            }
        }

        public string ApplicationTitle
        {
            get
            {
                return "Zoo";
            }
        }

        public string PageName
        {
            get
            {
                return "Animals";
            }
        }

    }
}

In this class we see a constructor, that for this demo sake i put it in there, just to show you that you really don’t need any code for logic part, the properties will do the trick. There are 2 properties here and 2 member variable declares. “zoo” is here to get the information from the model, and “Zoo” it’s a property used to access  him. selectedAnimal is a member that the binding will modify when the user click on the listBox (we will talk about that later), and like “zoo”, selectedAnimal also have a property named SelectedAnimal (obviously) that is used in the same manner.

Note that the RaisePropertyChanged() method must be used for the View to update it’s bindings when a property change.

If we finished here we can move to the xaml part (:) the most interesting one). It looks this way:

<Grid x:Name="LayoutRoot"
	      Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel"
		            Grid.Row="0"
		            Margin="24,24,0,12">
            <TextBlock x:Name="ApplicationTitle"
			           Text="{Binding ApplicationTitle}"
			           Style="{StaticResource PhoneTextNormalStyle}" />
            <TextBlock x:Name="PageTitle"
			           Text="{Binding PageName}"
			           Margin="-3,-8,0,0"
			           Style="{StaticResource PhoneTextTitle1Style}" />
        </StackPanel>

            <!--You should look from here !-->

        <Grid x:Name="ContentGrid"
		      Grid.Row="1">
            <StackPanel Name="stackPanel1" >
                <ListBox Name="listBox1"  ItemsSource="{Binding Path=Zoo.zooPark}" SelectedItem="{Binding SelectedAnimal,Mode=TwoWay}" Height="333">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Vertical" >
                                <TextBlock Text="{Binding Name, StringFormat='Animal Name : {0}'}" FontSize="18"/>
                                <TextBlock Text="{Binding Age, StringFormat='Animal Age : {0}'}"  FontSize="18"/>
                                <TextBlock Text=" "/>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
                <TextBlock Text="{Binding Path=SelectedAnimal.Name,Mode=TwoWay}"
			           FontSize="40" Height="68" />

            </StackPanel>

        </Grid>
    </Grid>

 

Basically what i’ve done here is that i have dropped an stack pannel into the content grid and in him i declared a ListBox and a TextBlock . Now, perhaps you wonder why did i use a ListBox.ItemTemplate in such a simple application?well the answer is because it looks much cleaner when you do this. The 2  TextBlock‘s are used to display the Name and Age properties and i used a StringFormater again just to look cleaner.

Until now we’ve discussed about the design of the page. now i’ts time to move to logic :) . First thing to do is to bind the ItemSource property of the ListBox to the Zoo property from the MainViewModel.cs class and the zoo member  have the zooPark field because he is of type ZooParK (remember from the  ZooPark class ;) ), so the best way to do it is to write something like this:

ItemsSource="{Binding Path=Zoo.zooPark}"

To access the Name and Age fields, the TextBlock’s  Text property is also made with binding  one with Name, and one with Age (note that you don’t have to specify again the binding to the root object because the ListBox Item Source already defined it, and since theese textBlocks are members of the ListBox they will automatically inherit the binding) .

OK, at this point if you run your application you will be able to see the listBox been populated. To make the name appear in the TextBlock below, first thing you do , is to bind the TextBlock to the SelectedAnimal property (that is in class MainViewModel) and with “.” you specify that you want to access the Name field, and in the ListBox  you set the SelectedItem property to bind with SelectedAnimal too. In that way when u click on an item in the listbox, the SelectedItem property will get modified with the curent item selected, and since the TextBlock below is binded to the same property, he will display it.

So that’s all. Hope this helps;).

Happy Coding.

Cya!