有点晚了,但我认为这可能仍然有用:
根据 A.Pissicat、Surfen 和 Ben McMillan 的代码(和评论),我更新GridViewColumnVisibilityManager
如下:
/// <summary>
/// Used to hide the attached <see cref="GridViewColumn"/> and prevent the user
/// from being able to access the column's resize "gripper" by
/// temporarily setting both the column's width and style to
/// a value of 0 and null (respectively) when IsVisible
/// is set to false. The prior values will be restored
/// once IsVisible is set to true.
/// </summary>
public static class GridViewColumnVisibilityManager
{
public static readonly DependencyProperty IsVisibleProperty =
DependencyProperty.RegisterAttached(
"IsVisible",
typeof(bool),
typeof(GridViewColumnVisibilityManager),
new UIPropertyMetadata(true, OnIsVisibleChanged));
private static readonly ConditionalWeakTable<GridViewColumn, ColumnValues> OriginalColumnValues = new ConditionalWeakTable<GridViewColumn, ColumnValues>();
public static bool GetIsVisible(DependencyObject obj) => (bool)obj.GetValue(IsVisibleProperty);
public static void SetIsVisible(DependencyObject obj, bool value) => obj.SetValue(IsVisibleProperty, value);
private static void OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is GridViewColumn gridViewColumn))
{
return;
}
if (!GetIsVisible(gridViewColumn))
{
// Use GetOrCreateValue to ensure
// we have a place to cache our values.
// Any previous values will be overwritten.
var columnValues = OriginalColumnValues.GetOrCreateValue(gridViewColumn);
columnValues.Width = gridViewColumn.Width;
columnValues.Style = gridViewColumn.HeaderContainerStyle;
// Hide the column by
// setting the Width to 0.
gridViewColumn.Width = 0;
// By setting HeaderContainerStyle to null,
// this should remove the resize "gripper" so
// the user won't be able to resize the column
// and make it visible again.
gridViewColumn.HeaderContainerStyle = null;
}
else if (gridViewColumn.Width == 0
&& OriginalColumnValues.TryGetValue(gridViewColumn, out var columnValues))
{
// Revert back to the previously cached values.
gridViewColumn.HeaderContainerStyle = columnValues.Style;
gridViewColumn.Width = columnValues.Width;
}
}
private class ColumnValues
{
public Style Style { get; set; }
public double Width { get; set; }
}
}
如果您希望在隐藏列时使用特定HeaderContainerStyle
Style
而不是,请替换:null
gridViewColumn.HeaderContainerStyle = columnValues.Style;
和
gridViewColumn.HeaderContainerStyle = Application.Current.TryFindResource(@"disabledColumn") as Style;
并更改@"disabledColumn"
为您要使用的任何名称。