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 小时前
C# 设计模式大全(第一弹|7种)
microsoft·设计模式·微软·c#·.net·.netcore
格林威2 小时前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
向上的车轮3 小时前
熟悉C#如何转TypeScript——SDK与包引用
开发语言·typescript·c#
baivfhpwxf20234 小时前
DataGrid 中增加选择列 功能实现
ui·wpf
CSharp精选营4 小时前
Dispose 不释放?C# 资源泄漏的 3 种隐蔽场景排查
c#·资源泄漏
unicrom_深圳市由你创科技6 小时前
LabVIEW和C#在工业控制中的应用差异是什么?
fpga开发·c#·labview
唐青枫7 小时前
C#.NET Consul + Steeltoe 深入解析:服务注册发现、健康检查与微服务接入
c#·.net
czhc11400756637 小时前
winform 330 跨线程 异步
wpf·线程·winform
DowneyJoy7 小时前
【Unity3D补充知识点】常用数据结构分析-集合(List<T>)
数据结构·unity·c#·list
格林威7 小时前
Baumer相机铝型材表面划伤长度测量:实现损伤量化评估的 5 个关键技术,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·工业相机