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>
相关推荐
枫叶林FYL1 天前
项目九:异步高性能爬虫与数据采集中枢 —— 基于 Crawl<sub>4</sub>AI 与 Playwright 的现代化数据采集平台 项目总览
爬虫·python·深度学习·wpf
她说彩礼65万1 天前
WPF 多值转换器
wpf
无心水2 天前
【分布式利器:金融级】金融级分布式架构开源框架全景解读
人工智能·分布式·金融·架构·开源·wpf·金融级框架
她说彩礼65万2 天前
WPF 转换器
wpf
WPF工业上位机2 天前
匠心研智造,同心赴新程-WPF硬件通讯之串口&Socket
wpf
爱炸薯条的小朋友3 天前
C#由窗体原子表溢出造成的软件闪退,根本原因补充
开发语言·c#·wpf
晚风一隅3 天前
阿里云盘古存储系统:EB级分布式存储的架构革命与技术突破
wpf
步步为营DotNet4 天前
深挖.NET 11:.NET Aspire 在云原生应用状态管理的创新与实践
云原生·.net·wpf
He BianGu4 天前
【项目】WPF VisionMaster 4.0 项目介绍和开发文档
c#·wpf·流程图·开发文档·机器视觉·visionmaster
He BianGu4 天前
【笔记】在WPF中PriorityBinding的详细介绍
笔记·wpf