WPF: How to hide GridViewColumn using XAML?

后端 未结 10 690
北海茫月
北海茫月 2020-12-05 09:59

I have the following object in App.xaml


        
            

        
10条回答
  •  孤街浪徒
    2020-12-05 10:52

    You best bet is probably to create a custom control by inheriting from the GridView class, adding the required columns, and exposing a meaningful property to show/hide a particular column. Your custom GridView class could look like this:

    using System;
    using System.Windows.Controls;
    
    namespace MyProject.CustomControls
    {
        public class CustomGridView : GridView
        {
            private GridViewColumn _fixedColumn;
            private GridViewColumn _optionalColumn;
    
            public CustomGridView()
            {
                this._fixedColumn = new GridViewColumn() { Header = "Fixed Column" };
                this._optionalColumn = new GridViewColumn() { Header = "Optional Column" };
    
                this.Columns.Add(_fixedColumn);
                this.Columns.Add(_optionalColumn);
            }
    
            public bool ShowOptionalColumn
            {
                get { return _optionalColumn.Width > 0; }
                set
                {
                    // When 'False' hides the entire column
                    // otherwise its width will be set to 'Auto'
                    _optionalColumn.Width = (!value) ? 0 : Double.NaN;
                }
            }
    
        }
    }
    

    Then you can simply set that property from XAML like in this example:

    
        
            
                
                    
                
            
    
            
                
                    
                
            
        
    
    

    Optionally, you could make the 'CustomGridView.ShowOptionalColumn' a DependencyProperty to be able to use it as a binding target.

提交回复
热议问题