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>
相关推荐
FuckPatience1 天前
WPF 给一个界面上的按钮应用同一种样式
wpf
Polevne2 天前
WPF\MAUI\Avalonia Dispatcher
wpf
Ares-Wang3 天前
wpf 图表制作 LiveCharts
wpf
A_nanda3 天前
c#WPF开发常见问题
开发语言·c#·wpf
Wang's Blog5 天前
AI Agent白手起家60: 多智能体架构解析与 LangGraph 入门
人工智能·架构·wpf
.Peter5 天前
.NET/WPF 程序在部分 Windows 电脑无法保存用户环境变量:使用 DPAPI 实现安全兼容
windows·信息安全·c#·.net·wpf·环境变量·dpapi
dalong106 天前
WPF:3D型材模型
3d·wpf
一念春风7 天前
文件透明加密(C、C#)
c语言·c#·wpf
yanaiding8 天前
C# WPF 独立开发看图工具 PixSight 经验介绍(二)—— 水印模块开发实录
图像处理·c#·wpf·个人开发
我是苏苏10 天前
WPF开发01:基础控件及常用模板篇
开发语言·c#·html·wpf