wpf relativesourcebind

文章介绍了如何在XAML中通过RelativeSource绑定机制来访问并绑定父组件的属性。示例代码展示了绑定ComboBox的ItemsSource和Button的IsEnabled属性到父View的数据Context,以及使用DataTrigger改变形状颜色的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要绑定到父的某些属性,试验记录一下 结果

基本上,您需要使用RelativeSource绑定(bind)。

标准方法是查找特定类型控件祖先(或父代):

{Binding DataContext.PropertyName, RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type YourViewsNamespace:YourParentView}}}

假设您的父 View 的 View 模型设置为其DataContext,则此绑定(bind)将对其进行访问… DataContext是该 View 的DataContext,例如。设置为DataContext的 View 模型。因此,PropertyName属性是该 View 模型的公共(public)属性。

比如

<ComboBox Grid.Column="3" Width="120" ItemsSource="{Binding DataContext.SfList,RelativeSource={RelativeSource AncestorType={x:Type Window},Mode=FindAncestor}}" DisplayMemberPath="SF_ID"  />

<Button IsEnabled="{Binding DataContext.IsWork,RelativeSource={RelativeSource AncestorType={x:Type Window}, Mode=FindAncestor},Converter={StaticResource Boolean2BooleanReConverter}}" Content="PLC" Command="{Binding PCommand}" />

这里的Combox 就是依据某个参数的值“3”,绑定生成的。
里面的ComboBox绑定的数据如上所示
在这里插入图片描述

<DataTrigger Binding="{Binding DataContext.DependencyProperty,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:UserControlName}}}" Value="On">
                                                <Setter Property="Fill" Value="Red" />
                                        </DataTrigger>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值