2010-06-25 8 views
1

Je ne sais pas selon les données du MVVM sur le contrôle.Problème avec MVVM. Liste dynamique des grilles

J'ai une collection de voitures. Je veux grouper par type (par exemple Sedan, Combi, Hatchback) et dépend du nombre de types de grilles d'impression de

Alors:

5 voitures: 2 x berline, 2 x Combi, 1 x sportcar.

Je veux imprimer 3 grilles.

Comment ça marche avec MVVM.

Répondre

3

Voici un exemple de code. Si vos listes de voitures peuvent changer, vous devriez plutôt utiliser ObservableCollections ou implémenter INotifyPropertyChanged sur votre 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 derrière:

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

Merci beaucoup :) – user278618

Questions connexes