WPF RelativeSource

RelativeSource 类在 WPF 中提供了以下几种模式:

RelativeSource Self:指定当前元素作为相对源。可以在当前元素的属性中绑定到自身的属性。

示例:

html 复制代码
<TextBlock Text="{Binding Text, RelativeSource={RelativeSource Self}}" />

RelativeSource TemplatedParent:指定模板的父级元素作为相对源。在自定义控件模板中使用,绑定到模板的父级元素的属性。

示例:

html 复制代码
<ControlTemplate TargetType="local:CustomButton">
    <Border Background="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}">
        <!-- 模板定义 -->
    </Border>
</ControlTemplate>

RelativeSource FindAncestor:指定在祖先元素中进行查找。可以指定 AncestorType 来指示查找的具体类型,在找到匹配的第一个祖先后进行绑定。

示例:

html 复制代码
<TextBlock Text="{Binding DataContext.PropertyName, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}"/>

RelativeSource PreviousData:在绑定集合数据时,绑定到前一个数据项的属性。只能在 ItemsControl 或具有类似行为的控件中使用。

示例:

html 复制代码
<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Name}" 
                       Foreground="{Binding PreviousData.Completed, 
                                   Converter={StaticResource StatusToColorConverter}}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
相关推荐
FuckPatience12 小时前
WPF xaml中的 xmlns:d=“http://schemas.microsoft.com/expression/blend/2008“ 的使用
ui·wpf
就是有点傻14 小时前
WPF加载动画
ui·wpf
kylezhao201914 小时前
WPF Binding 从入门到精通
wpf
Poetinthedusk2 天前
WPF应用跟随桌面切换
开发语言·wpf
小北方城市网2 天前
MongoDB 分布式存储与查询优化:从副本集到分片集群
java·spring boot·redis·分布式·wpf
听麟2 天前
HarmonyOS 6.0+ 智慧出行导航APP开发实战:离线地图与多设备位置协同落地
华为·wpf·harmonyos
笨蛋不要掉眼泪2 天前
Spring Boot + RedisTemplate 数据结构的基础操作
java·数据结构·spring boot·redis·wpf
LcVong3 天前
WPF MediaPlayer获取网络视频流当前帧并展示图片完整范例
网络·wpf
bugcome_com4 天前
WPF数据绑定入门:从传统事件到5种绑定模式
wpf
LateFrames4 天前
我用 WPF 做了一个 “苍蝇飞舞” 的屏保
ui·wpf