wpfdata-bindingdatagriddatatemplatedatagridtemplatecolumn

Datagrid Column Header Template Binding Not working for Multiple Instances


I have a datagrid Template Column which contains a header template and a cell template. This datagrid sits in a view called ViewOne. Multiple instances of ViewOne are being injected into another view - ViewTwo.

Here lies the problem: When I create a single instance of ViewOne in ViewTwo, everything works perfectly. However, when I create multiple instances of it, everything still works perfectly except for the button in the header template. I have tried to figure out why, but I can't seem to place a finger on the problem, and it is really strange because even the button in the cell template works fine, and they are hooked up pretty much the same way.

Here is the code:

<DataGridTemplateColumn Width="Auto">
                            <DataGridTemplateColumn.Header>
                                <Button Background="Transparent" Height="Auto" Command="{Binding DataContext.AddRowCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
                                Width="Auto" BorderBrush="Transparent" ToolTip="Add new row">
                                  <Image Source="/DemoApp.Resource;component/Icons/Default/add-icon.png"/>
                                </Button>
                           </DataGridTemplateColumn.Header>

                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Width="Auto" Background="Transparent" Height="Auto"  
                                    ToolTip="Delete selected row" BorderBrush="Transparent"
                                    Command="{Binding DataContext.RemoveCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
                                    CommandParameter="Separator">
                                        <Image Source="/DemoApp.Resource;component/Icons/Default/Delete.ico"/>
                                    </Button>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Solution

  • I finally discovered the issue. I simply changed the AncestorType of the button command binding from Datagrid to UserControl. Apparently the binding was working for the first instance of the UserControl in the collection, but not others. Was kinda weird but it worked.

    <Button Background="Transparent" Height="Auto" Command="{Binding DataContext.AddRowCommand, RelativeSource={RelativeSource AncestorType= UserControl}}" ...>
    
    ...
    </Button