欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

WPF DataGrid控件隐藏栏显示

程序员文章站 2022-07-13 22:39:35
...

WPF DataGrid控件隐藏栏显示

一、先添加一个类BindingProxy:

public class BindingProxy : Freezable
    {
        protected override Freezable CreateInstanceCore() => new BindingProxy();

        public object Data
        {
            get => GetValue(DataProperty);
            set => SetValue(DataProperty, value);
        }

        public static readonly DependencyProperty DataProperty =
            DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
    }

二、MainWindow.xaml代码:

<Grid>
        <DataGrid>
            <DataGrid.Resources>
                <local:BindingProxy x:Key="DataContextProxy" Data="{Binding}"/>
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTextColumn Header="姓名" Width="100"/>
                <DataGridTextColumn Header="性别" Width="100"/>
                <DataGridTextColumn Header="电话" Width="100"/>
                <DataGridTextColumn Header="邮箱" Visibility="{Binding Data.IsShow,Source={StaticResource DataContextProxy}}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>

三、MainWindow.xaml.cs代码:

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            IsShow = Visibility.Hidden;

            this.DataContext = this;
        }

        private Visibility isShow;

        public Visibility IsShow
        {
            get { return isShow; }
            set { isShow = value; }
        }
    }

效果:
(隐藏邮箱一栏)
WPF DataGrid控件隐藏栏显示