Bind to DataContext property from within a DataGrid

Problem

Consider the following DataGrid:

<sdk:DataGrid ItemsSource="{Binding LineItems}" >
    <sdk:DataGridCheckBoxColumn Binding="{Binding IsValueTrue }" />
</sdk:DataGrid>

The DataGridCheckBoxColumn assumes that the objects contained in the collection “LineItems” each have a boolean property named “IsValueTrue” which will be displayed in the column for each record.  However, if you want to bind to a property on the ViewModel, you would reference the “LayoutRoot” in the binding:

<sdk:DataGrid ItemsSource="{Binding LineItems}" >
    <sdk:DataGridCheckBoxColumn Binding="{Binding ElementName=LayoutRoot, Path=DataContext.IsViewModelValueTrue}" />
</sdk:DataGrid>

This works great for basic columns, but, for whatever reason, it does not work within a DataGridTemplateColumn.  Consider the following DataGrid:

<!-- NOTE: This is incorrect -->
<sdk:DataGrid ItemsSource="{Binding LineItems}" >
  <sdk:DataGridTemplateColumn>
    <sdk:DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
        <CheckBox IsChecked="{Binding ElementName=LayoutRoot, Path=DataContext.IsViewModelValueTrue}" />
      </DataTemplate>
    </sdk:DataGridTemplateColumn.CellTemplate>
  </sdk:DataGridTemplateColumn>
</sdk:DataGrid>

The checkbox will display as unchecked regardless of the value of IsViewModelValueTrue.

Solution

In the interest of time, the solution provided by my man Sergey Barskiy and is located at: http://dotnetspeak.com/index.php/2010/05/elementname-binding-inside-silverlight-datagrid/.  Actually, I don’t know him from Adam, but his solution worked.  Sergey, if you ever read this, feel free to link to my blog. :)

Extra Nerd Cred (and ad)

Visit the link above via my own new url shortener: konv.es/TLpTy4.

Visit the link you’re on now with: konv.es/ocKxQ1.

Posted on November 28, 2011 at 2:23 pm by Steve Konves · Permalink
In: C#, Silverlight

Leave a Reply