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>
相关推荐
Macbethad9 小时前
如何用WPF做工控设置界面
java·开发语言·wpf
csdn_aspnet9 小时前
WPF 做一个简单的电子签名板(一)
c#·wpf
玖笙&9 小时前
✨WPF编程进阶【7.2】:动画类型(附源码)
c++·c#·wpf·visual studio
·心猿意码·18 小时前
WPF中TemplatePart机制详解
wpf
FuckPatience2 天前
WPF 使用UserControl / ContentControl显示子界面
wpf
wangnaisheng2 天前
【WPF】WrapPanel的用法
wpf
源之缘-OFD先行者3 天前
10 万雷达点迹零卡顿回放:WPF + Vortice.Direct2D 多线程渲染实战
wpf
猫林老师3 天前
Flutter for HarmonyOS开发指南(九):测试、调试与质量保障体系
flutter·wpf·harmonyos
LateFrames3 天前
做【秒开】的程序:WPF / WinForm / WinUI3 / Electron
electron·c#·wpf·winform·winui3·claude code
beyond谚语4 天前
第四章 依赖项属性
wpf