Jonathan Birkholz

How Do I Hide Columns With a Wpf GridView

In my current project we ran across a problem where we wanted to hide certain columns in a grid view based on domain criteria.

We looked into custom grid headers, attached properties, custom controls, etc. Every path lead to a very complex and more importantly custom solution.

I spent an afternoon playing around and came up with this solution which we are using today.

It’s simple, easy to follow, and doesn’t require any custom code. All it uses is the power of style and triggers. The biggest knock is OH NOES! you have a bit of duplication in your xaml.

What is it?

Well, you set the ‘View’ property in your style. Then you utilize style triggers to swap out the View.

Yup.. easy.. simple… no mess.

Example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<Style x:Key="listViewStyle" TargetType="ListView">
<Setter Property="View">
<Setter.Value>
<GridView>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Salary"
DisplayMemberBinding="{Binding Salary}" />
</GridView>
</Setter.Value>
</Setter>
<Style.Triggers>
<DataTrigger Binding="{Binding HideCols}" Value="True">
<Setter Property="View">
<Setter.Value>
<GridView>
<GridViewColumn Header="Name"
DisplayMemberBinding="{Binding Name}" />
</GridView>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>

WPF