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 :

[xml]<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>[/xml]

Advertisements

One thought on “How do I hide columns with a Wpf GridView?

Comments are closed.