WPF RelativeSource属性-目标对象类型易错

上一篇转载了RelativeSource的三种用法,其中第二种用法 较常见,这里记录一下项目中曾经发生错误的地方,以防自己哪天忘记了,又犯了同样错误---WPF RelativeSource属性-CSDN博客

先回顾一下:

控件关联其父级容器的属性------AncestorType

详细介绍下AncestorLevel,它指的是以Bingding目标控件为起点的层级偏移量,S1的偏移量是1,G2的偏移量是2,G1是偏移量3,AncestorType指的是要找的目标对象的类型。值得注意的是AncestorLevel必须参考AncestorType使用,如上面设置了AncestorType={x:Type Grid},则Bingding在寻找时会忽略非Grid的控件,此时G2的偏移量是1,G1的偏移量是2,StackPanel被忽略。

错误代码:

cs 复制代码
<TabControl>
    <TabItem
        Width="150"
        Height="30"
        Header="TabItem1"
        IsSelected="True">
        <ScrollViewer MaxHeight="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabItem, AncestorLevel=1}}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid Grid.Row="0">
                    <TextBlock
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        FontSize="100"
                        Text="用户控件" />
                </Grid>
            </Grid>
        </ScrollViewer>
    </TabItem>
</TabControl>

Page界面显示效果:文字显示不全,只显示了高度为30的文字部分

问题出在这句话:<ScrollViewer MaxHeight="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabItem, AncestorLevel=1}}">

AncestorType=TabItem,往上查找第一个TabItem控件,其Height="30",这样ScrollViewer的MaxHeight=30,直接造成显示不全

改前台代码AncestorType=TabControl,如下

cs 复制代码
<TabControl>
    <TabItem
        Width="150"
        Height="30"
        Header="TabItem1"
        IsSelected="True">
        <ScrollViewer MaxHeight="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TabControl, AncestorLevel=1}}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition />
                </Grid.RowDefinitions>
                <Grid Grid.Row="0">
                    <TextBlock
                        HorizontalAlignment="Center"
                        VerticalAlignment="Center"
                        FontSize="100"
                        Text="用户控件" />
                </Grid>
            </Grid>
        </ScrollViewer>
    </TabItem>
</TabControl>

Page界面显示效果:文字显示完整,所以使用RelativeSource查找目标类型 AncestorType时,一定要仔细!

相关推荐
最美的不是下雨天1 小时前
为什么要用async、await ?
c#
拾忆,想起1 小时前
Redisson 分布式锁的实现原理
java·开发语言·分布式·后端·性能优化·wpf
NullReference1 小时前
记一次WPF程序界面卡死的情况
c#
秋月的私语2 小时前
wpf程序启动居中并且最小化到托盘修复记录
c#
weixin_464078073 小时前
wpf依赖注入驱动的 MVVM实现(含免费源代码demo)
wpf
木心爱编程5 小时前
C++程序员速通C#:从Hello World到数据类型
c++·c#
※※冰馨※※5 小时前
【c#】 使用winform如何将一个船的图标(ship.png)添加到资源文件
开发语言·windows·c#
咕白m6256 小时前
C# 实现 Word 与 TXT 文本格式互转
c#·.net
beyond谚语7 小时前
一、WPF入门介绍+Grid和StackPanel布局介绍+实战模拟Notepad++页面布局
wpf
CPU不够了7 小时前
WPF常见问题清单
wpf·自适应