当AutoGenerateColumns = True时,有没有办法隐藏DataGrid中的特定列?

时间:2010-10-22 19:10:05

标签: wpf xaml datagrid

我有一个使用AutoGenerateColumns = True绑定到DataTable的WPF 4.0 DataGrid。列是动态的,但我知道总会有一个名为ID的列,我想隐藏这一列。有没有办法可以做到这一点?

7 个答案:

答案 0 :(得分:34)

在您的数据网格中订阅AutoGeneratingColumn事件,事件argsDataGridAutoGeneratingColumnEventArgs)具有列名称和“Cancel”,如果列名称为然后设置ID Cancel = true。应该做的。

答案 1 :(得分:9)

您可以使用行为(可重复使用的代码)来完成这项工作......这样您就可以使用将列可见性集中在一个地方的属性。

用法:

<Window
...
 xmlns:extension="clr-namespace:WpfControlLibrary.Extension;assembly=WpfControlLibrary">

<DataGrid ...
    extension:DataGridBehavior.UseBrowsableAttributeOnColumn="True">

...

public class YourObjectItem
{
    [Browsable(false)]
        public Assembly Assembly { get; set; }

代码:

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace HQ.Wpf.Util.Behaviors
{
    /// <summary>
    /// Using this behavior on a dataGRid will ensure to display only columns with "Browsable Attributes"
    /// </summary>
    public static class DataGridBehavior
    {
        public static readonly DependencyProperty UseBrowsableAttributeOnColumnProperty =
            DependencyProperty.RegisterAttached("UseBrowsableAttributeOnColumn",
            typeof(bool),
            typeof(DataGridBehavior),
            new UIPropertyMetadata(false, UseBrowsableAttributeOnColumnChanged));

        public static bool GetUseBrowsableAttributeOnColumn(DependencyObject obj)
        {
            return (bool)obj.GetValue(UseBrowsableAttributeOnColumnProperty);
        }

        public static void SetUseBrowsableAttributeOnColumn(DependencyObject obj, bool val)
        {
            obj.SetValue(UseBrowsableAttributeOnColumnProperty, val);
        }

        private static void UseBrowsableAttributeOnColumnChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var dataGrid = obj as DataGrid;
            if (dataGrid != null)
            {
                if ((bool)e.NewValue)
                {
                    dataGrid.AutoGeneratingColumn += DataGridOnAutoGeneratingColumn;
                }
                else
                {
                    dataGrid.AutoGeneratingColumn -= DataGridOnAutoGeneratingColumn;
                }
            }
        }

        private static void DataGridOnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var propDesc = e.PropertyDescriptor as PropertyDescriptor;

            if (propDesc != null)
            {
                foreach (Attribute att in propDesc.Attributes)
                {
                    var browsableAttribute = att as BrowsableAttribute;
                    if (browsableAttribute != null)
                    {
                        if (!browsableAttribute.Browsable)
                        {
                            e.Cancel = true;
                        }
                    }

                    // As proposed by "dba" stackoverflow user on webpage: 
                    // https://stackoverflow.com/questions/4000132/is-there-a-way-to-hide-a-specific-column-in-a-datagrid-when-autogeneratecolumns
                    // I added few next lines:
                    var displayName = att as DisplayNameAttribute;
                    if (displayName != null)
                    {
                        e.Column.Header = displayName.DisplayName;
                    }
                }
            }
        }
    }
}

答案 2 :(得分:4)

其他可能性为Visibility.Collapsed

    private void dataGrid_AutoGeneratingColumn(object sender, 
        DataGridAutoGeneratingColumnEventArgs e)
    {
        //Set properties on the columns during auto-generation 
        switch (e.Column.Header.ToString())
        {
            case "rownameYouWantToHide":
                e.Column.Visibility = Visibility.Collapsed;
                break;
        }
    }

答案 3 :(得分:1)

我不能说4,但是在3.5 SP1中是不可能的,至少没有注册我想不惜一切代价避免的事件。

您可以做的是将生成代码更改为AutoGenerateColumns=False,然后将您关注的列放在XAML中,因为基础数据仍将完全放在列中

            <dg:DataGridTextColumn Header="Display" Binding="{Binding DisplayName}"/>
            <dg:DataGridTextColumn Header="Host" Binding="{Binding HostName}"/>
            <dg:DataGridTextColumn Header="Database" Binding="{Binding Database}"/>
            <dg:DataGridTextColumn Header="Username" Binding="{Binding Username}"/>
            <dg:DataGridTextColumn Header="Password" Binding="{Binding Password}"/>

这将允许您显示与基础模型相关的唯一列,并根据需要更改Header以显示,因此您不依赖于Property模型上的名称。

答案 4 :(得分:0)

我不会说这是一个很好的解决方案......但是......你可以再拥有一个抽象层 例如,假设你有一个像这样的对象:

public class Foo
{
    public string Id { get; set; }

    public string Property2 { get; set; }

    public string Property3 { set; get; }
}

您不希望ID为列,因此您需要创建新对象

public class Foo2
{
    public string Property2 { get; set; }

    public string Property3 { set; get; }
}

然后将Foo映射/转换为Foo2,你就完成了。

另一种可能的方式(并非总是可能)是将访问修饰符更改为内部

public class Foo
{
    internal string Id { get; set; }

    public string Property2 { get; set; }

    public string Property3 { set; get; }
}

这样您就不会生成Id列。

答案 5 :(得分:0)

我最近做到了这一点,并希望分享我的解决方案:

我刚刚创建了一个视图模型,我希望数据网格遵循该模型,对于希望其忽略的字段(即,不为其自动生成列),只需将这些字段设置为私有即可。像魅力一样工作,不需要不必要的代码。

例如,这是我传递给包含数据网格的视图的视图模型。我只需将我不想将的字段设置为私有列即可获得所需的一切,这些示例显示在示例中的“ FullPath”字段中。我知道这可能并非在每种情况下都可行,但对我来说很好。

namespace dev
{   
    /// <summary>
    /// View model for tag list view in data grid
    /// </summary>
    public class TagDataViewModel : BaseViewModel
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="path">The JSONPath to this item</param>
        public TagDataViewModel(string path)
        {
            FullPath = path;
        }

        /// <summary>
        /// Gets and sets the JSONPath to this item
        /// </summary>
        private string FullPath { get; set; }

        /// <summary>
        /// Gets the name
        /// </summary>
        public string Name => ProjectHelpers.GetPropertyValue(FullPath, "Name");

        /// <summary>
        /// Gets the address
        /// </summary>
        public string Address => ProjectHelpers.GetPropertyValue(FullPath, "Address");

        /// <summary>
        /// Gets the data type
        /// </summary>
        public string DataType => ProjectHelpers.GetPropertyValue(FullPath, "DataType");

        /// <summary>
        /// Gets the scan rate
        /// </summary>
        public string ScanRate => ProjectHelpers.GetPropertyValue(FullPath, "ScanRate");

        /// <summary>
        /// Gets the scaling type
        /// </summary>
        public string ScalingType => ProjectHelpers.GetPropertyValue(FullPath, "ScalingType");
    }
}

答案 6 :(得分:0)

我使用Browsable属性和Visibility: Collapsed

实现了这一目标

型号

class CourseModel
{
    [Description("")]
    [ReadOnly(false)]
    public bool Select { get; set; } = true; // Checkbox

    [Description("Course ID")]
    [ReadOnly(true)]
    [Browsable(false)]
    public string ID { get; set; } // Hidden column

    [Description("Course Title")]
    [ReadOnly(true)]
    public string Title { get; set; }
}

自定义控件扩展名:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

namespace MyProject.FrontEnd.Controls
{
    class CustomDataGrid : DataGrid
    {
        // Take attributes of POCO, if available (https://stackoverflow.com/a/17255496/979621)

        protected override void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e)
        {
            try
            {
                base.OnAutoGeneratingColumn(e);
                var propertyDescriptor = e.PropertyDescriptor as PropertyDescriptor;
                e.Column.Header = propertyDescriptor.Description;
                e.Column.IsReadOnly = propertyDescriptor.IsReadOnly;
                e.Column.Visibility = propertyDescriptor.IsBrowsable 
                                      ? Visibility.Visible 
                                      : Visibility.Collapsed;
            }
            catch
            {
                // ignore; retain field defaults
            }
        }
    }
}

ViewModel

public ObservableCollection<CourseModel> Courses { get; set; }

XAML

<Window 
    ...
    xmlns:controls="clr-namespace:MyProject.FrontEnd.Controls" 
    ...
>
...
<controls:CustomDataGrid x:Name="courses" 
    ItemsSource="{Binding Path=Courses, Mode=TwoWay, 
                  NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" />