Project Description
This project uses an Expression Blend attached behavior to add a column-chooser context menu to a WPF Datagrid.

Users' column-visibility and column-order choices are persisted to and restored from the WPF application's user-specific config files.

 

Image of WPF Datagrid with column-chooser context menu



 

 


By adding this behavior to any WPF datagrid, users will be able to configure the datagrid from a context menu by right-clicking on any grid column heading:

 

  • Configure datagrid columns to show by checking/unchecking the column names
  • Configure datagrid column order by dragging and dropping column headings
  • Configure frozen datagrid columns by selecting the "Freeze Columns" menu item
  • Configure numbered datagrid row headers by selecting the "Row Numbers" menu item


The behavior saves the user's column selections and ordering choices to a user configuration file, and re-applies them the next time the user sees the grid.

The behavior can also maintain a label in a group box containing the datagrid, showing the number of columns visible and the total columns available. Simply enclose your datagrid in a GroupBox control to invoke labelling.

Instructions for using the WPF DataGrid Configuration Behavior

1. Add these namespaces and references to your xaml file. If you don't have Expression Blend or the SDK loaded, you can get the required libraries from the Blend SDK downloadable from this link.

        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 
        xmlns:Behaviors="clr-namespace:Behaviors"



2. Add the <i:Interaction.Behaviors> block to your Datagrid.

                <DataGrid x:Name="yourDataGridName">
                    <i:Interaction.Behaviors>
                        <Behaviors:WPFDataGridConfigurationBehavior 
                        VisibleColumns="{Binding Source={StaticResource Settings}, Path=Default.yourDataGridNameVisibleColumns}"
                        DisplayIndexes="{Binding Source={StaticResource Settings}, Path=Default.yourDataGridNameDisplayIndexes}"
                        />
                    </i:Interaction.Behaviors>                   
                </DataGrid>
  



3. Add the following two entries to your application's Settings.settings file, replacing 'yourDataGridName' with the name of your datagrid. (You must give your DataGrid a name or the behavior won't work.)

    <Setting Name="yourDataGridNameVisibleColumns" Type="System.String" Scope="User">
      <Value Profile="(Default)" />
    </Setting>
    <Setting Name="yourDataGridNameDisplayIndexes" Type="System.String" Scope="User">
      <Value Profile="(Default)" />
    </Setting>



4. Add the WPFDataGridConfigurationBehavior.cs file (see Downloads) to your project.

Last edited Feb 4, 2012 at 6:16 PM by onejbsmith, version 35