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>
相关推荐
大G的笔记本26 分钟前
生产级 Spring Boot 网关简单实现方案
wpf
稷下元歌2 天前
七天学会plc加机器视觉之AI 接入 外设模块开发全详细操作文档(全程配套视频按文档实操)
python·sql·qt·贪心算法·r语言·wpf·时序数据库
happyprince2 天前
11-Hugging Face Transformers 分布式与并行系统深度分析
分布式·c#·wpf
加号32 天前
【WPF】 基于 Canvas 读取并渲染 DXF 文件的技术指南
c#·wpf
AC赳赳老秦3 天前
用 OpenClaw 整理团队技术分享:自动提取 PPT 内容、生成文字稿、同步到知识库
开发语言·python·自动化·powerpoint·wpf·deepseek·openclaw
闪电悠米3 天前
黑马点评-秒杀优化-03_blocking_queue_async_order
数据库·分布式·oracle·junit·wpf·lua
kingwebo'sZone3 天前
WPF 在(WrapPanel父级使用可以自动换行)每个 TextBlock 显示一行数据(竖排,垂直)
wpf
闪电悠米3 天前
黑马点评-秒杀优化-02_lua_precheck
开发语言·redis·分布式·缓存·junit·wpf·lua
FuckPatience4 天前
WPF 获取一个控件某个依赖属性的默认绑定方式
wpf
加号34 天前
【WPF】 ListView 数据绑定:从列表呈现到复杂交互的完整实践
wpf·交互