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>
相关推荐
超级种码2 小时前
Redis:Redis高可用——副本、哨兵和集群
数据库·redis·wpf
棉晗榜2 小时前
wpf给Border添加闪烁边框
wpf
Derrick_itRose2 小时前
DevExpress笔记WPF(2)Data Editors and Controls(基础编辑器)
笔记·编辑器·wpf
曹天骄18 小时前
Cloudflare KV 使用教程(基于 Wrangler 项目)
wpf
摘星编程1 天前
Flutter for OpenHarmony 实战:Dialog 对话框详解
flutter·wpf
ou.cs1 天前
WPF TreeView 自动展开所有节点:附加行为(Attached Behavior)保姆级实现教程
c#·.net·wpf
一念春风1 天前
可视化视频编辑(WPF C#)
开发语言·c#·wpf
bugcome_com3 天前
C# 字符串拼接全面指南
c#·.net·wpf