Bind to DataContext property from within a DataGrid


Consider the following DataGrid:

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

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}" />

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}" >
        <CheckBox IsChecked="{Binding ElementName=LayoutRoot, Path=DataContext.IsViewModelValueTrue}" />

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


In the interest of time, the solution provided by my man Sergey Barskiy and is located at:  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:

Visit the link you’re on now with:

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

Leave a Reply