Command binding inside a DataGridTemplateColumn

Anthares picture Anthares · Jul 5, 2011 · Viewed 10.6k times · Source

I am working on a Silverlight application which makes an extensive use of Prism, the MVVM pattern and MEF. For several reasons, I have chosen to follow a View-first approach.

In one of the Views there is a DataGrid, and one of the columns of this grid is a DataGridTemplateColumn, which has just a Button.

I'd like to define both a Command and a CommandParameter on the Button. The Command should be a DelegateCommand of the ViewModel. CommandParameter should be the SelectedItems list coming straight out of the dataGrid.

I've tried several approaches to do this, but either Command or CommandParameter are null.

It follows the code that I originally wrote:

<sdk:DataGridTemplateColumn>
    <sdk:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Width="15" Height="15" Content=">" 
                    Command="{Binding UpdateSearchParametersCommand}" 
                    CommandParameter="{Binding SelectedItems, ElementName=dataGrid}">
        </DataTemplate>
    </sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>

Could someone advice me on what the best way to go about it is?

Thanks in advance, Gianluca.

Answer

Rachel picture Rachel · Jul 5, 2011

Your current binding is pointing to DataGridRowItem.UpdateSearchParametersCommand. You need to change it to point to DataGrid.DataContext.UpdateSearchParametersCommand

<sdk:DataGrid x:Name=dataGrid>
    <sdk:DataGridTemplateColumn>
        <sdk:DataGridTemplateColumn.CellTemplate>
            <DataTemplate>
                <Button Width="15" Height="15" Content=">" 
                        Command="{Binding DataContext.UpdateSearchParametersCommand, ElementName=dataGrid}" 
                        CommandParameter="{Binding SelectedItems, ElementName=dataGrid}">
            </DataTemplate>
        </sdk:DataGridTemplateColumn.CellTemplate>
    </sdk:DataGridTemplateColumn>
</sdk:DataGrid>