tags:

views:

135

answers:

1

Hi,

I don't know according to MVVM show data on control.

I have a collection of cars.

I want group their by type (eg. Sedan, Combi, Hatchback) and depends of number of types print grids.

So :

5 cars: 2 x sedan, 2 x Combi, 1 x sportcar.

So I want to print 3 grids.

How do it to be ok with MVVM.

+2  A: 

Below is some sample code. If your lists of cars can change you should use ObservableCollections instead or implement INotifyPropertyChanged on your viewmodel. XAML:

<Window x:Class="TestApp.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Height="300" Width="300">
    <Grid>
        <ListBox ItemsSource="{Binding Path=CarTypes}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Path=Key}" />
                        <ListBox ItemsSource="{Binding Path=Value}" DisplayMemberPath="Name" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>
    </Grid>
</Window>

Code behind:

using System.Collections.Generic;
using System.Windows;

namespace TestApp
{
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();

            DataContext = new CarsVM();
        }
    }

    public class CarsVM
    {
        public CarsVM()
        {
            CarTypes = new Dictionary<string, List<Car>>();

            // You want to populate CarTypes from some model.
            CarTypes["sedan"] = new List<Car>() {new Car("Honda Accord"), new Car("Toyota Camry")};
            CarTypes["musclecar"] = new List<Car>() { new Car("Chevy Camaro"), new Car("Dodge Challenger") };
            CarTypes["suv"] = new List<Car>() { new Car("Chevy Tahoe") };
        }

        public Dictionary<string, List<Car>> CarTypes { get; private set; } 
    }

    public class Car
    {
        public Car(string name)
        {
            Name = name;
        }
        public string Name { get; set; }
    }
}
Wallstreet Programmer
Thank you very much :)