WPF XamDataGrid如何绑定字段Label到父级ViewModel的属性?
问题核心原因
Infragistics XamDataGrid 的 Field 对象不属于WPF可视化树的一部分,直接编写绑定默认会取到单条数据对应的Dog对象上下文,无法直接向上访问父级DogsVM。
解决方案1:使用Freezable数据代理(兼容性最好)
这种方案不依赖控件命名,适配所有场景。
第一步:创建绑定代理类
public class BindingProxy : Freezable { protected override Freezable CreateInstanceCore() => new BindingProxy(); public object Data { get => GetValue(DataProperty); set => SetValue(DataProperty, value); } public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy)); }
第二步:在页面/用户控件的资源中声明代理
<UserControl.Resources> <!-- 此处的Binding会拿到当前页面的DataContext也就是DogsVM实例 --> <local:BindingProxy x:Key="VmProxy" Data="{Binding}" /> </UserControl.Resources>
第三步:修改Field的Label绑定
<igDP:Field Name="DogName" Label="{Binding Data.ViewName, Source={StaticResource VmProxy}}" AllowEdit="False" />
解决方案2:使用x:Reference引用(写法更简洁)
不需要额外写代理类,适合快速修改的场景。
第一步:给XamDataGrid添加命名
<igDP:XamDataGrid x:Name="DogsGrid" DataSource="{Binding CollectionView}"> <!-- 其余原有配置 --> </igDP:XamDataGrid>
第二步:修改Field的Label绑定
<igDP:Field Name="DogName" Label="{Binding DataContext.ViewName, Source={x:Reference DogsGrid}}" AllowEdit="False" />
注意事项
你原有配置中Name="DogName "属性末尾多了一个多余空格,需要删除才能正确映射到Dog类的DogName属性。
内容的提问来源于stack exchange,提问作者John John
相关产品推荐
相关产品推荐

