C#/WPF: Make a GridViewColumn Visible=false?

后端 未结 5 667
北恋
北恋 2021-02-13 02:15

Does anyone know if there is an option to hide a GridViewColumn somehow like this:


    
        

        
5条回答
  •  臣服心动
    2021-02-13 02:31

    Here is another solution based on setting the column's width to zero. I have modified it a little. It now works like this:

    1. Bind the header's visibility to a boolean property of the ViewModel, using a bool-to-visibility converter
    2. Use an attached property on the header to set the column's width to zero

    Here is the code.

    XAML:

    
        
    

    BooleanToVisibilityConverter:

    public class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool param = bool.Parse(value.ToString());
            if (param == true)
                return Visibility.Visible;
            else
                return Visibility.Collapsed;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    Attached behavior GridViewBehaviors.CollapseableColumn:

    public static readonly DependencyProperty CollapseableColumnProperty =
         DependencyProperty.RegisterAttached("CollapseableColumn", typeof(bool), typeof(GridViewBehaviors),
        new UIPropertyMetadata(false, OnCollapseableColumnChanged));
    
    public static bool GetCollapseableColumn(DependencyObject d)
    {
        return (bool)d.GetValue(CollapseableColumnProperty);
    }
    
    public static void SetCollapseableColumn(DependencyObject d, bool value)
    {
        d.SetValue(CollapseableColumnProperty, value);
    }
    
    private static void OnCollapseableColumnChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        GridViewColumnHeader header = sender as GridViewColumnHeader;
        if (header == null)
            return;
    
        header.IsVisibleChanged += new DependencyPropertyChangedEventHandler(AdjustWidth);
    }
    
    static void AdjustWidth(object sender, DependencyPropertyChangedEventArgs e)
    {
        GridViewColumnHeader header = sender as GridViewColumnHeader;
        if (header == null)
            return;
    
        if (header.Visibility == Visibility.Collapsed)
            header.Column.Width = 0;
        else
            header.Column.Width = double.NaN;   // "Auto"
    }
    

提交回复
热议问题