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>
相关推荐
qq_392397121 天前
Redis常用操作
数据库·redis·wpf
三千道应用题2 天前
WPF学习笔记(25)MVVM框架与项目实例
wpf
厦门德仔2 天前
【WPF】WPF(样式)
android·java·wpf
三千道应用题3 天前
WPF学习笔记(16)树控件TreeView与数据模板
wpf
✎ ﹏梦醒͜ღ҉繁华落℘3 天前
WPF学习(四)
学习·wpf
zzyzxb3 天前
WPF中依赖属性和附加属性
wpf
✎ ﹏梦醒͜ღ҉繁华落℘3 天前
WPF学习(动画)
学习·wpf
weixin_447103583 天前
Wpf布局之Canvas面板!
wpf
葬歌倾城4 天前
waferMap图像渲染
c#·wpf
甄天4 天前
WPF路由事件:冒泡、隧道与直接全解析
c#·wpf·visual studio