【问题标题】:Why Browsable(false) does not hide columns in DataGrid为什么 Browsable(false) 不隐藏 DataGrid 中的列
【发布时间】:2015-10-04 12:12:49
【问题描述】:

在我的 WPF 应用程序中,我想通过将 [Browsable(false)] 添加到某些属性来隐藏具有绑定 ItemsSource 的 DataGrid 中的列 但是,无论有无 Browsable(false),所有列都是可见的。

我的模特:

public class Room : INotifyPropertyChanged
{
    private int id;
  ...
    [Browsable(false)]
    public int Id
    {
        get
        {
            return this.id;
        }
        set
        {
            this.id = value;
            this.OnPropertyChanged("Id");
        }
    }
    ...
    public Room()
    {
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged;
        if (propertyChangedEventHandler != null)
        {
            propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

查看:

<DataGrid Grid.Row="1" ItemsSource="{Binding Rooms}" SelectedItem="{Binding SelectedRoom, Mode=TwoWay}" />

如何使用 Browsable(false) 隐藏列?

【问题讨论】:

    标签: c# wpf visual-studio datagrid


    【解决方案1】:

    您可以通过连接 DataGrid 上的 AutoGeneratingColumn 事件来隐藏它们(请参阅https://stackoverflow.com/a/3794324/4735446)。

    public class DataGridHideBrowsableFalseBehavior : Behavior<DataGrid>
    {
        protected override void OnAttached()
        {
            AssociatedObject.AutoGeneratingColumn += AssociatedObject_AutoGeneratingColumn;
            base.OnAttached();
        }
    
        private void AssociatedObject_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            if (((PropertyDescriptor)e.PropertyDescriptor).IsBrowsable == false)
                e.Cancel = true;
        }
    }
    
    
    <DataGrid
        ItemsSource="{Binding Path=DataGridSource, Mode=OneWay}"
        AutoGenerateColumns="true">
            <i:Interaction.Behaviors>
                <behaviors:DataGridHideBrowsableFalseBehavior>
                 </behaviors:DataGridHideBrowsableFalseBehavior>
            </i:Interaction.Behaviors>
    </DataGrid>
    

    【讨论】:

      【解决方案2】:

      恐怕你不能。 Browsable 属性只影响可视化设计器的 Properties 视图,在运行时没有任何影响...

      欲了解更多信息,请查看MSDN page about BrowsableAttribute.

      【讨论】:

        【解决方案3】:

        不要在你的代码中调用this.OnPropertyChanged("Id");

        【讨论】:

          猜你喜欢
          • 2011-06-28
          • 1970-01-01
          • 1970-01-01
          • 2017-07-31
          • 2021-02-09
          • 2014-08-28
          • 2012-03-13
          • 2015-08-18
          • 1970-01-01
          相关资源
          最近更新 更多