MVVM问题。动态网格列表

时间:2010-06-25 10:15:47

标签: c# wpf mvvm

我不知道根据MVVM显示控制数据。

我有一系列汽车。

我希望按类型分组(例如,Sedan,Combi,Hatchback)并且取决于打印网格的类型数量。

所以:

5辆车: 2 x轿车,2 x Combi,1 x sportcar。

所以我想打印3个网格。

如何使用MVVM。

1 个答案:

答案 0 :(得分:3)

下面是一些示例代码。如果您的汽车列表可以更改,则应使用ObservableCollections或在您的viewmodel上实现INotifyPropertyChanged。 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>

代码背后:

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; }
    }
}