李sir_Blog

博客园 首页 联系 订阅 管理
  705 随笔 :: 58 文章 :: 134 评论 :: 193万 阅读

 当一个Binding有明确的数据来源时我们可以通过为Source或者ElementName赋值的办法让binding与之关联。有些时候我们不能确定作为Source的对象叫什么名字,但知道它与作为Binding目标的对象在UI布局上有相应的关系,比如控件自己关联自己的某个属性、关联自己某级容器的数据。这时候我们就要使用Binding的RelativeSource属性。这种办法的意思是指当前元素和绑定源的位置关系。

  • 第一种关系: Self

举一个最简单的例子:在一个StackPanel中,有一个TextBlock。

  1.  
    <TextBlock FontSize="18" FontWeight="Bold" Margin="10"
  2.  
    Background="Red" Width="80" Height="{Binding RelativeSource={RelativeSource Self},Path=Width}">MultiBinding Sample</TextBlock>

如果想让textbox的width和height相同,通过设置属性Height="{Binding RelativeSource={RelativeSource Self},Path=Width}" 就可以实现。

还可以这样写:Height="{Binding RelativeSource={RelativeSource Mode=Self},Path=Width}",Mode是RelativeSource类的枚举。“RelativeSource Mode=Self”调用了类的枚举Mode,“RelativeSource Self”使用了类的静态属性Self,达到的目的是一样的。

  • 第二种关系:TemplatedParent

例如为一个Button写一个样式,修改Button为椭圆型。同时需要椭圆的背景色和Button的背景色相同。

  1.  
    <Style TargetType="{x:Type Button}">
  2.  
    <Setter Property="Background" Value="Green"/>
  3.  
    <Setter Property="Template">
  4.  
    <Setter.Value>
  5.  
    <ControlTemplate TargetType="{x:Type Button}">
  6.  
    <Grid>
  7.  
    <Ellipse>
  8.  
    <Ellipse.Fill>
  9.  
    <SolidColorBrush Color="{Binding Path=Background.Color,RelativeSource={RelativeSource TemplatedParent}}"/>
  10.  
    </Ellipse.Fill>
  11.  
    </Ellipse>
  12.  
    </Grid>
  13.  
    </ControlTemplate>
  14.  
    </Setter.Value>
  15.  
    </Setter>
  16.  
    </Style>

在这个例子中 TemplateParent就是指的Button

  • 第三种关系:AncestorType

指定绑定源为某个父元素

  1.  
    <Grid>
  2.  
    <Label Background = {Binding Path=Background, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}/>
  3.  
    </Grid>

这个例子中Label的背景色和Grid的背景色一样。

posted on   李sir  阅读(247)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-12-23 Android自定义Seekbar拖动条式样
2015-12-23 android自定义seekBar
2015-12-23 android国际化(多语言)
2015-12-23 android 自定义日历控件
2015-12-23 android 常用类
点击右上角即可分享
微信分享提示