0

So I have a WPF DataGrid bound to an ObservableCollection, which contains a single instance of a class - for example:

Public Class parent
    Public Property title As String [...]
    Public Property someCommonThing as Integer [...]

Public Class Child Inherits Parent
    Public Property name As String [...]
    Public Property address As String [...]

Public Class Window1
    Dim oc As ObservableCollection(Of Object) = New ObservableCollection(Of Object)
    oc.Add(New Child())
    dataGrid.ItemsSource = oc

there are many child classes with different properties, hence why I can't easily define the datagrid columns directly.

I want to be able to hide certain parent properties from the datagrid (for example, never show the title property in the datagrid), while still being able to use it for databinding elsewhere (e.g. a label).

Is this possible? I can't think how to do it without manually specifying every column for every possible class instead of using the databinding.

simonalexander2005
  • 4,338
  • 4
  • 48
  • 92

1 Answers1

1

When automatically generating columns you can change the per-property behavior using Data Annotations, in this case specifically the BrowsableAttribute class:

<Browsable(False)>

Annotating your property with this will prevent a column from being generated when using the following event handler on the AutoGeneratingColumn event of the DataGrid.

Private Sub OnAutoGeneratingColumn(sender As Object, e As DataGridAutoGeneratingColumnEventArgs)
    If Not DirectCast(e.PropertyDescriptor, PropertyDescriptor).IsBrowsable Then
        e.Cancel = True
    End If
End Sub

Remember to add the DataAnnotations assembly to your project.

Bas
  • 26,772
  • 8
  • 53
  • 86