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>
相关推荐
Chris _data13 天前
WPF 学习第三天 — Modbus RTU 串口通信
hadoop·学习·wpf
布吉岛的石头14 天前
Java 程序员第 43 阶段05:微服务整合大模型,跨服务调用架构设计实战,Seata分布式事务实战
wpf
步步为营DotNet14 天前
基于.NET Aspire 实现云原生应用的高效监控与可观测性
云原生·.net·wpf
芒鸽14 天前
HarmonyOS 分布式开发实战:设备协同、数据共享与跨设备迁移
分布式·wpf·harmonyos
Volunteer Technology14 天前
Flink状态管理与容错(二)
大数据·flink·wpf
happyprince15 天前
07_verl-Trainer模块详解
人工智能·架构·wpf·强化学习
bugcome_com15 天前
WPF + Prism 技术指南与实战项目(二、模板搭建)
wpf
小满Autumn15 天前
log4net 日志框架 — 从配置到实战速查手册
笔记·c#·.net·wpf·上位机·log4net
政沅同学16 天前
基于 C# WPF + HALCON 的工业视觉算法工具框架(开源)
开发语言·c#·wpf
happyprince16 天前
03_verl-设计理念与核心原理
wpf