tags:

views:

272

answers:

1

I have a page with a view model. I am trying set the binding source of a combo box from a templated DataGrid column to the view model. It gives me a null reference error.

This is my XAML:

<navigation:Page.Resources>
    <vm:SiteViewModel x:Key="viewModel" />
</navigation:Page.Resources>
<navigation:Page.DataContext>       
    <Binding Source="{StaticResource viewModel}" />
</navigation:Page.DataContext>

...

<data:DataGrid ItemsSource="{Binding CurrentSite.Contacts}"> 
    <data:DataGrid.Columns>
    <data:DataGridTemplateColumn Header="Role">
                            <data:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>                                
                                    <ComboBox ItemsSource="{Binding Path=Roles, Source=????}"  >
                                        <ComboBox.ItemTemplate>
                                            <DataTemplate>
                                                <StackPanel Orientation="Horizontal">
                                                    <TextBlock Text="{Binding Path=RoleName}" VerticalAlignment="Center" />
                                                </StackPanel>
                                            </DataTemplate>
                                        </ComboBox.ItemTemplate>
                                    </ComboBox>
                                </DataTemplate>
                            </data:DataGridTemplateColumn.CellTemplate>
                        </data:DataGridTemplateColumn>
    </data:DataGrid.Columns>
</data:DataGrid>
A: 

First off you could simplify your xaml to:

<navigation:Page.DataContex>
  <vm:SiteViewModel />
</navigation:Page.DataContext>

The other issue is that once you get inside the datagrid which has a different datacontext you can no longer reach back up to the page datacontext. In order to get around this I recommend using Dan Wahlin's DataContextProxy control which makes it easy to reach back out. Using that you would add:

<navigation:Page.DataContex>
  <vm:SiteViewModel />
</navigation:Page.DataContext>
<navigation:Page.Resources>    
 <controls:DataContextProxy x:Key="DataContextProxy" />
</navigation:Page.Resources>

...

<data:DataGrid ItemsSource="{Binding CurrentSite.Contacts}">     
 <data:DataGrid.Columns>    
  <data:DataGridTemplateColumn Header="Role">                            
   <data:DataGridTemplateColumn.CellTemplate>                                
    <DataTemplate>                                                                    
      <ComboBox ItemsSource="{Binding Source={StaticResource DataContextProxy},Path=DataSource.Roles}">
...
      </ComboBox>                                
    </DataTemplate>                            
   </data:DataGridTemplateColumn.CellTemplate>                        
  </data:DataGridTemplateColumn>    
 </data:DataGrid.Columns>
</data:DataGrid>
Bryant