Friday, April 22, 2011

How to use WPF GridSplitter inside Grid


In this article I am going to demonstrate how to use GridSplitter inside Grid using simple example.


Gridsplitter provides facility to change width of columns and height of rows at runtime to the users. You can add GridSplitter control similar to other controls inside Grid. You can add GridSplitter control with existing content but the best approach to add it in separate row or column. You should remember that GridSplitter resize entire column or row not only single cell. You can use ColumnSpan or RowSpan to achieve this. You can also specify Horizontal/Vertical alignment to stretch GridSplitter across column or row. GridSplitter can be declared in nested Grid. You can change width or height of GridSplitter to make it more visible.

You can set ShowsPreview property to True if you don’t want to resize your column or row on mouse move during dragging. You can see shadow while resizing column or row if this property set to true. By default value of this property is set to false. You can also set DragIncrement property if you want to resize some fix amount of change on drag.

<Grid Width="250" Height="150" VerticalAlignment="Top">
        <Grid.RowDefinitions>
            <RowDefinition Height="20" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="90"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row ="0" Grid.Column="0" Text="Name:"
                   HorizontalAlignment="Right" />
        <TextBox Grid.Row ="0" Grid.Column="2"/>
        <GridSplitter Grid.Column="1" Grid.RowSpan="3" Width="2"
                      ShowsPreview="False" DragIncrement="10"
                      HorizontalAlignment="Stretch"
                      VerticalAlignment="Stretch" />
        <GridSplitter Grid.Row="1" Grid.ColumnSpan="3" Height="2"
                      ShowsPreview="False" DragIncrement="20"
                      HorizontalAlignment="Stretch"
                      VerticalAlignment="Stretch" />
        <TextBlock Grid.Row ="2" Grid.Column="0" Text="City:"
                   HorizontalAlignment="Right" />
        <TextBox Grid.Row ="2" Grid.Column="2"/>
        <Button Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3"
                Content="Click Me!" Height="25" Width="100" 
                Margin="0,10,0,0"
                HorizontalAlignment="Center" VerticalAlignment="Top"/>
</Grid>


2 comments: