How to bind DataGridColumn.Visibility?

前端 未结 9 1942
悲哀的现实
悲哀的现实 2020-12-10 03:46

I have an issue similar to the following post:

Silverlight DataGridTextColumn Binding Visibility

I need to have a Column within a Silverlight DataGrid be vis

9条回答
  •  被撕碎了的回忆
    2020-12-10 03:58

    Here's the solution I've come up with using a little hack.

    First, you need to inherit from DataGrid.

    public class DataGridEx : DataGrid
    {
        public IEnumerable HiddenColumns
        {
            get { return (IEnumerable)GetValue(HiddenColumnsProperty); }
            set { SetValue(HiddenColumnsProperty, value); }
        }
    
        public static readonly DependencyProperty HiddenColumnsProperty =
            DependencyProperty.Register ("HiddenColumns", 
                                         typeof (IEnumerable), 
                                         typeof (DataGridEx),
                                         new PropertyMetadata (HiddenColumnsChanged));
    
        private static void HiddenColumnsChanged(object sender,
                                                 DependencyPropertyChangedEventArgs args)
        {
            var dg = sender as DataGrid;
            if (dg==null || args.NewValue == args.OldValue)
                return;
    
            var hiddenColumns = (IEnumerable)args.NewValue;
            foreach (var column in dg.Columns)
            {
                if (hiddenColumns.Contains ((string)column.GetValue (NameProperty)))
                    column.Visibility = Visibility.Collapsed;
                else
                    column.Visibility = Visibility.Visible;
            }
        }
    }
    

    The DataGridEx class adds a new DP for hiding columns based on the x:Name of a DataGridColumn and its descendants.

    To use in your XAML:

    
        
                                Header="Count"
                                Binding={Binding CountOfItems}"
        
    
    

    You need to add these to your ViewModel or whatever data context you use.

    private IEnumerable _hiddenColumns;
    public IEnumerable HiddenColumns
    {
        get { return _hiddenColumns; }
        private set
        {
            if (value == _hiddenColumns)
                return;
    
            _hiddenColumns = value;
            PropertyChanged (this, new PropertyChangedEventArgs("HiddenColumns"));
        }
    }
    
    public void SomeWhereInYourCode ()
    {
        HiddenColumns = new List {"uiDataCountOfItems"};
    }
    

    To unhide, you only need to remove the corresponding name from the list or recreate it without the unhidden name.

提交回复
热议问题