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 :

<style x:Key="listViewStyle" TargetType="ListView">
    <setter Property="View">
        </setter><setter .Value>

            <gridview>
                <gridviewcolumn Header="Name"
                                DisplayMemberBinding="{Binding Name}" />
                <gridviewcolumn Header="Salary"
                                DisplayMemberBinding="{Binding Salary}" />
            </gridview>

        </setter>

    </style><style .Triggers>
        <datatrigger Binding="{Binding HideCols}" Value="True">

            <setter Property="View">
                </setter><setter .Value>

                    <gridview>
                        <gridviewcolumn Header="Name"
                                        DisplayMemberBinding="{Binding Name}" />
                    </gridview>

                </setter>

        </datatrigger>
    </style>

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

  • #1
    Posted by RredCat on January 8th, 2009 at 3:42 am

    To set Width of column’s Name as ’0′ isn’t easy way?

  • #2
    Posted by Tdot on October 2nd, 2009 at 2:43 pm

    Setting Width to 0 does not prevent a user from resizing the column after the fact. This solution is better.

Share your opinion! Post your thoughts.