3

In my WPF apllication I want to hide column in DataGrid with binding ItemsSource by adding [Browsable(false)] to some properties But, with or without Browsable(false) all columns are visible.

My model:

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;
}

View:

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

How can I use Browsable(false) to hide columns?

paparazzo
  • 44,497
  • 23
  • 105
  • 176
tauri
  • 293
  • 2
  • 6
  • 18

3 Answers3

2

You can hide them by hooking up the AutoGeneratingColumn Event on your DataGrid (see 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>
bslein
  • 332
  • 1
  • 12
0

You can't, I'm afraid. The Browsable attribute only affects the Properties view of the visual designer, it has NO effect during runtime...

For more info, check the MSDN page about BrowsableAttribute.

almulo
  • 4,918
  • 1
  • 20
  • 29
-1

Don't call this.OnPropertyChanged("Id"); in your code.

maxshuty
  • 9,708
  • 13
  • 64
  • 77