RelativeSource FindAncestor问题

时间:2009-08-24 14:26:34

标签: wpf listview binding relativesource

以下是代码:

<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>

基本上我要做的是让标题中的TextBlock跟随整列的宽度。

它不起作用:文本块的宽度始终与内部文本匹配。有任何想法吗?... 提前谢谢!

1 个答案:

答案 0 :(得分:14)

您的代码中存在两个问题

  1. GridViewColumn不是TextBox的可视祖先,它的祖先是GridViewColumnHeader
  2. 您应该绑定到GridViewColumnHeader的ActualWidth,而不是Width(如果未指定Width,则它将是无效的数字)
  3. 所以你的代码变成了:

                  <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>