65.9K
CodeProject is changing. Read more.
Home

DoubleClickCollapseGridSplitterBehavior

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (6 votes)

Sep 9, 2010

CPOL
viewsIcon

15080

Answer to a very interesting question on StackOverflow...

Weird name, I know!!!

Found this very interesting question on StackOverflow recently on how to extend a GridSplitter to expand/collapse a grid cell by pressing a button…

“I'm looking to extend the GridSplitter in some way to add a button which when click expands or collapses the control to one of the specified sides of the splitter.”

And I decided to give it a try… But to make it super simple, I will only support collapsing of cells (by double clicking on the GridSplitter) using behaviors (Expression Blend SDK).

Here is my behavior:

public class DoubleClickCollapseGridSplitterBehavior : Behavior<GridSplitter>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.PreviewMouseDoubleClick += 
		new System.Windows.Input.MouseButtonEventHandler
		(AssociatedObject_PreviewMouseDoubleClick);
    }

    protected override void OnDetaching()
    {
        this.AssociatedObject.PreviewMouseDoubleClick -= 
		new System.Windows.Input.MouseButtonEventHandler
		(AssociatedObject_PreviewMouseDoubleClick); 
        base.OnDetaching();
    }

    void AssociatedObject_PreviewMouseDoubleClick
		(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        GridSplitter splitter = sender as GridSplitter;
        Grid parent = splitter.Parent as Grid;

        int row = (int)splitter.GetValue(Grid.RowProperty);
        int col = (int)splitter.GetValue(Grid.ColumnProperty);

        double splitterHeight = (double)splitter.GetValue(GridSplitter.HeightProperty);
        double splitterWidth = (double)splitter.GetValue(GridSplitter.WidthProperty);

        if (double.IsNaN(splitterWidth))
        {
            parent.RowDefinitions[row].SetValue
		(RowDefinition.HeightProperty, new GridLength(splitterHeight));
        }
        else
        {
            parent.ColumnDefinitions[col].SetValue
		(ColumnDefinition.WidthProperty, new GridLength(splitterWidth));
        }
    }
}

And to use it:

<GridSplitter>
    <i:Interaction.Behaviors>
        <local:DoubleClickCollapseGridSplitterBehavior />
    </i:Interaction.Behaviors>
</GridSplitter>

Very simple and this should also work on Silverlight (not tested yet).

As always, here is the code.