WPF DataGrid控件隐藏栏显示

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控件隐藏栏显示

上一篇:WPF_DataGrid


下一篇:WPF在数据列使用枚举时,通过枚举列设置DataGrid单元格或者行的样式