About databinding and composite views

A couple of days ago i had a databound ItemsControl (collection of Model.Cell) which instantiated sub views (with their own viewmodel).

 <Grid.Resources>
  <DataTemplate x:Key="CellTemplate">
   <views:CellView />
  </DataTemplate>
 </Grid.Resources>
 <ItemsControl 
   ItemTemplate="{StaticResource CellTemplate}" 
   ItemsSource="{Binding Cells}" />
</Grid>

Because each CellViewModel needs to know which cell they manage i used the following dirty hack:

public CellView() 
{
 Loaded += CellView_Loaded; 
}

void CellView_Loaded(object sender, RoutedEventArgs e) 
{
 DataContext = new CellViewModel(DataContext);
}

Later on that day i realised there was a much cleaner solution: Let the BoardViewModel expose a collection of ViewModels.CellViewModel instead of Model.Cell. What a relief that i don’t have to use the Loaded event hack :)

This entry was posted on Tuesday, October 13th, 2009 at 16:44 and is filed under Patterns, Silverlight, WPF. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply