RelativeSource FindAncestor issue
Asked Answered
R

1

5

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!

Rajasthani answered 24/8, 2009 at 14:26 Comment(0)
P
14

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>
Pozsony answered 24/8, 2009 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.