Search code examples
c#wpfwpfdatagriddatagridrowheader

Binding DataGridRowHeader button tooltip to row object properties


I have a button in my DataGridRowHeader template that I am positioning on the right-hand side of my columns.

The nice thing about this layout is when you click on the button it doesn't select the row, as it would if you located it in a column.

The issue I'm finding now is that I'm trying to bind the row's object properties, for example in the button's ToolTip. It keeps coming back blank, even if I hard-code it in. The same sort of binding on Visibility works fine.

How can I fix the ToolTip?

<DataGrid.RowHeaderTemplate>
    <DataTemplate>
        <Grid>
            <Button x:Name="btnSelectParent"
                    Template="{StaticResource SelectParentButtonStyle}"
                    Height="15" Width="15" 
                    Margin="0,0,-669,0" 
                    HorizontalAlignment="Right"
                    VerticalAlignment="Top"
                    ToolTipService.ShowOnDisabled="True"
                    Visibility="{Binding DataContext.ShowSelectParentBtn, RelativeSource={RelativeSource AncestorType=DataGridRow}, Converter={StaticResource bool2VisibilityConverter}}" >

                <Button.ToolTip>
                    <TextBlock TextAlignment="Left" 
                               Foreground="Black" 
                               FontWeight="Normal" 
                               Text="{Binding DataContext.ParentBtnMessage, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
                </Button.ToolTip>

            </Button>
        </Grid>
    </DataTemplate>
</DataGrid.RowHeaderTemplate>

Solution

  • DataGridRow is not a visual ancestor of a Button in a RowHeaderTemplate but DataGridRowHeader is:

    Visibility="{Binding DataContext.ShowSelectParentBtn, RelativeSource={RelativeSource AncestorType=DataGridRowHeader}, Converter={StaticResource bool2VisibilityConverter}}"
    

    Your second issue is that the Tooltip resides in its own element tree. You could solve this by binding the Tag property of the Button to the DataContext of the DataGridRowHeader and then bind to this property using the PlacementTarget of the Tooltip:

    <Button x:Name="btnSelectParent"
            ...
            Tag="{Binding Path=DataContext, RelativeSource={RelativeSource AncestorType=DataGridRowHeader}}">
        <Button.ToolTip>
            <ToolTip>
                <TextBlock TextAlignment="Left" 
                           Foreground="Black" 
                           FontWeight="Normal" 
                           Text="{Binding PlacementTarget.Tag.ParentBtnMessage, RelativeSource={RelativeSource AncestorType=ToolTip}}"/>
            </ToolTip>
        </Button.ToolTip>
    </Button>