当前位置: 首页 > news >正文

wpf xaml数据绑定时,寻找数据源的几种方式 (RelativeSource)

wpf xaml数据绑定时,寻找数据源的几种方式 (RelativeSource)

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

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

<TextBlock Text="{Binding Text, RelativeSource={RelativeSource Self}}" />



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

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

 


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

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

 

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

<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"
Foreground="{Binding PreviousData.Completed,
Converter={StaticResource StatusToColorConverter}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

http://www.zskr.cn/news/2838.html

相关文章:

  • 背负冲击试验机的设计原理与性能优化
  • LangChain
  • 军工企业涉密网文件导出用什么系统?答案在这里
  • Gateway 网关坑我! 被这个404 问题折腾了一年?
  • LangChain DIfy区别
  • 2008-2025年各省高考真题含解析
  • KUKA机器人的WorkVisual编程软件(转载)
  • [译] 我最爱的PostgreSQL 18特性:虚拟生成列
  • nasm 的 Hello, world 在 Windows 10 x64 上
  • 实用指南:52.前端的后端模式:为每个客户端定制专属「管家服务」
  • Agilent 34401A台式万用表远程读表
  • 马克思,本就是一位独立研究者
  • 产品二期,从GPT5规划开始
  • Redis能抗住百万并发的秘密
  • 深入理解JNI、安全点与循环优化:构建高健壮性Java应用
  • 英语_阅读_fascinating facts about water_待读
  • 即时通讯小程序 - 实践
  • CF2112C
  • ICPC/XCPC 做题记录
  • ABC394F
  • LG11793
  • 【GitHub每日速递】无需提示词!Nano Bananary香蕉超市:AI绘画玩法多到停不下来
  • Drift数据库开发实战:类型安全的SQLite解决方案
  • DELPHI FireDAC连接EXCEL文件
  • 当我们红尘作伴,活得潇潇洒洒
  • 二叉树理论
  • 栈和队列总结
  • Python-课后题题目-1.1编程世界初探
  • 引用类型
  • CF1237C2