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>
相关推荐
Zhen (Evan) Wang1 天前
.NET 6 + Dapper + User-Defined Table Type
sqlserver·c#·.net·wpf
界面开发小八哥2 天前
界面控件DevExpress WPF v25.1预览 - 支持Windows 11系统强调色
windows·wpf·界面控件·devexpress·ui开发·.net 9
军训猫猫头2 天前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf
Pasregret2 天前
缓存与数据库一致性深度解析与解决方案
数据库·缓存·wpf
Java林间4 天前
Zookeeper是什么?基于zookeeper实现分布式锁
分布式·zookeeper·wpf
zizisuo4 天前
1.微服务拆分与通信模式
微服务·wpf
程序员秘密基地4 天前
基于c#,wpf,ef框架,sql server数据库,音乐播放器
sql·sqlserver·c#·.net·wpf
Zhen (Evan) Wang4 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
冰茶_5 天前
WPF特性分析
学习·microsoft·c#·wpf
qq_196055876 天前
最快打包WPF 应用程序
wpf