wpf DataGrid控制列是否显示,DataGrid列不会触发Visibility的转换器

DataGridTextColumn(以及所有 DataGridColumn 派生类)不是 Visual 或 FrameworkElement,它只是 DataGrid 的列配置对象,不属于 WPF 的可视化树 / 逻辑树。这导致:

RelativeSource={RelativeSource AncestorType=DataGrid} 无法定位到 DataGrid(因为列不在可视化树中,没有 "祖先" 元素);

下面的代码,列上面绑定Visibility是不会生效的,也不会触发ZybValueToVisibilityConverter转换,必须使用桥接模式:

xml 复制代码
<DataGridTextColumn
     MinWidth="85"
     Header="调试"
     Visibility="{Binding DataContext.ColumnShowControl, RelativeSource={RelativeSource AncestorType=DataGrid}, Converter={StaticResource ZybValueToVisibilityConverter}}" />   

解决方案:使用 Freezable 作为绑定桥接

这是 WPF 中解决 "非可视化元素绑定到可视化树数据" 的经典方案,通过 Freezable 对象作为桥梁,让列能访问到 DataGrid 的 DataContext。

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Module.PEIS.Helper
{
    public sealed class BindingProxy : Freezable
    {

        public Object Data
        {
            get { return (object)GetValue(DataProperty); }
            set { SetValue(DataProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Data.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(Object), typeof(BindingProxy), new PropertyMetadata(default(BindingProxy)));


        protected override Freezable CreateInstanceCore() => new BindingProxy();
    }
}

页面需要引用BindingProxy 类的命名空间

xml 复制代码
    xmlns:bindingProxy="clr-namespace:Module.PEIS.Helper"

步骤 2:修改 XAML 代码(关键)

xml 复制代码
<!-- 1. 在DataGrid的Resources中定义绑定桥接对象,绑定到DataGrid的DataContext -->
<DataGrid>
    <DataGrid.Resources>
       <bindingProxy:BindingProxy
           x:Key="ColumnBindingProxy"
           Data="{Binding DataContext, RelativeSource={RelativeSource AncestorType=DataGrid}}" />
   </DataGrid.Resources>

    <!-- 2. 修改DataGridTextColumn的Visibility绑定,通过桥接对象访问数据 -->
    <DataGridTextColumn
        MinWidth="85"
        Header="调试"
        Visibility="{Binding Data.ColumnShowControl, 
                            Source={StaticResource ColumnBindingProxy}, 
                            Converter={StaticResource ZybValueToVisibilityConverter}}"/>
</DataGrid>
相关推荐
△曉風殘月〆12 小时前
如何在WPF中捕获窗口外的事件
wpf
爱吃烤鸡翅的酸菜鱼2 天前
Java 事件发布-订阅机制全解析:从原生实现到主流中间件
java·中间件·wpf·事件·发布订阅
武藤一雄3 天前
WPF中ViewModel之间的5种通讯方式
开发语言·前端·microsoft·c#·wpf
CSharp精选营3 天前
都是微软亲儿子,WPF凭啥干不掉WinForm?这3个场景说明白了
c#·wpf·跨平台·winform
baivfhpwxf20233 天前
wpf TextBlock 控件如何根据内容换行?
wpf
亘元有量-流量变现3 天前
鸿蒙、安卓、苹果音频设备技术深度解析与开发实践
android·wpf·harmonyos·亘元有量·积分墙
软泡芙3 天前
【Bug】ReactiveUI WPF绑定中依赖属性不更新的问题分析与解决方案
java·bug·wpf
浪扼飞舟3 天前
WPF输入验证(ValidationRule)
java·javascript·wpf
IOFsmLtzR5 天前
Flink Agents 源码解读 --- (5) --- ActionExecutionOperator
microsoft·flink·wpf
廋到被风吹走6 天前
【AI】Codex 复杂任务拆解:从“一气呵成“到“步步为营“
人工智能·wpf