wpf 相对来源 FindAncestor 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1322729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:54:40  来源:igfitidea点击:

RelativeSource FindAncestor issue

wpflistviewbindingrelativesource

提问by Teodor

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.

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

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

它不起作用:文本块的宽度始终与里面的文本相匹配。有什么想法吗?...提前致谢!

回答by Thomas Levesque

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)
  1. GridViewColumn 不是 TextBox 的视觉祖先,它的祖先是 GridViewColumnHeader
  2. 您应该绑定到 GridViewColumnHeader 的 ActualWidth,而不是 Width(如果未指定 Width,它将是一个无效数字)

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>