Search code examples
wpflistviewbindingrelativesource

RelativeSource FindAncestor issue


Here is the code:

<GridViewColumn DisplayMemberBinding="{Binding Path=BookId}" Width="100">
    <GridViewColumn.Header>
        <Border BorderBrush="Black">
            <TextBlock Width="{Binding RelativeSource=
                                       {RelativeSource FindAncestor, 
                                       AncestorType={x:Type GridViewColumn}}, 
                                       Path=Width}" Text="ID">
                <TextBlock.ContextMenu>
                    <ContextMenu>item1</ContextMenu>
                </TextBlock.ContextMenu>
            </TextBlock>
            </Border>
    </GridViewColumn.Header>
</GridViewColumn>

Basically what i am trying to do is to make the TextBlock in the header follow the width of the whole column.

It is not working: the textblock's width always matches the text inside. Any ideas?... Thanks in advance!


Solution

  • There are two problems in your code

    1. the GridViewColumn is NOT a visual ancestor of the TextBox, its ancestor is a GridViewColumnHeader
    2. You should bind to the ActualWidth of the GridViewColumnHeader, not the Width (if Width is not specified, it will be an invalid number)

    So your code becomes :

                  <GridViewColumn
                                DisplayMemberBinding="{Binding Path=BookId}"
                                Width="100">
                    <GridViewColumn.Header>
                        <Border BorderBrush="Black" >
                            <TextBlock Text="ID" Width="{Binding RelativeSource=
                                                            {RelativeSource FindAncestor, 
                                                            AncestorType={x:Type GridViewColumnHeader}}, 
                                                            Path=ActualWidth}">
                                <TextBlock.ContextMenu>
                                    <ContextMenu>item1</ContextMenu>
                                </TextBlock.ContextMenu>
                            </TextBlock>
                            </Border>
                    </GridViewColumn.Header>
                </GridViewColumn>