Voici un exemple à illustrer en utilisant MVVM. Notez qu'il n'est pas nécessaire d'avoir une liste de contrôles usuels et en effet cela serait considéré comme incorrect d'un point de vue MVVM.
Ceci est basé sur le modèle d'application WPF par défaut dans Visual Studio.
Voici les classes concernées.
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null)
{
changed(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Container : ViewModelBase
{
private string m_Objective;
private ProblemCollection m_Problems;
public Container()
{
m_Problems = new ProblemCollection();
}
public string Objective
{
get { return m_Objective; }
set
{
m_Objective = value;
OnPropertyChanged("Objective");
}
}
public ProblemCollection Problems
{
get { return m_Problems; }
set
{
m_Problems = value;
OnPropertyChanged("Problems");
}
}
}
public class Problem : ViewModelBase
{
private string m_Name;
public string Name
{
get { return m_Name; }
set
{
m_Name = value;
OnPropertyChanged("Name");
}
}
}
public class ProblemCollection : ObservableCollection<Problem>
{
}
Et la fenêtre principale. Notez que j'ai commenté votre rectangle pour afficher les liaisons
<Window x:Class="StackOverflowDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock TextWrapping="Wrap" Text="{Binding Objective}" Grid.Column="0" VerticalAlignment="Center"
FontWeight="Bold" />
<ItemsControl ItemsSource="{Binding Problems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!--<Rectangle Stroke="Black" Height="20" Width="20" Margin="1,0" />-->
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
MainWindow.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Create dummy test data.
// Normally this will be passed to the window or set externally
var container = new Container();
container.Problems.Add(new Problem {Name = "Foo"});
container.Problems.Add(new Problem {Name = "Bar"});
container.Problems.Add(new Problem {Name = "hello"});
container.Problems.Add(new Problem {Name = "world"});
DataContext = container;
}
}
Ne répond pas directement à la question, mais peut-être d'une certaine utilité - http://stackoverflow.com/questions/1939403/mvvm-viewmodel-vs-mvc-viewmodel/1939606 # 1939606 –