Thmms
Thmms

Reputation: 11

Command - binding from DataGridTemplateColumn

<DataGrid ItemsSource="{Binding Occerences}" 
          AutoGenerateColumns="False"
          IsReadOnly="True">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Start index" Binding="{Binding Start}" />
        <DataGridTextColumn Header="End index"  />
        <DataGridTextColumn Header="Length"  />
        <DataGridTextColumn Header="Pattern"  />
        <DataGridTemplateColumn Header="Sequence">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Sequence" Command="{Binding SequenceCommand}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Export">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Button Content="Export" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>       
</DataGrid> 

<Button Content="Sequence" Command="{Binding SequenceCommand}" />

This is not working. How to bind to SequenceCommand (MyViewModel, ICommand SequenceCommand)?

I can't use frameworks (mvvm light tool kit, prism, etc).

Upvotes: 1

Views: 1209

Answers (1)

King King
King King

Reputation: 63377

The DataContext in DataTemplate for CellTemplate will be changed to bind to the current item where the SequenceCommand is not found. You have to set a RelativeSource to the DataGrid and set Path for DataContext.SequenceCommand like this:

<Button Content="Sequence" 
        Command="{Binding RelativeSource={RelativeSource AncestorType=DataGrid},
        Path=DataContext.SequenceCommand}" />

Upvotes: 5

Related Questions