Click here to Skip to main content
15,881,561 members
Articles / Desktop Programming / WPF

DockPanel Splitter Control for WPF

Rate me:
Please Sign up or sign in to vote.
4.50/5 (19 votes)
10 Aug 2009CPOL 213.4K   6.8K   55   43
A splitter control for the WPF DockPanel
Sample Image

Introduction

This control adds size adjustment functionality to elements of a DockPanel in the same way a GridSplitter can adjust the size of columns and rows in a Grid. When resizing the parent container, the elements will be resized proportionally unless the ProportionalResize property is set to False.

Using the Code

Add the OpenSourceControls namespace and add a DockPanelSplitter control after each panel you want to adjust. The DockPanel.Dock attribute controls which edge of the panel the splitter works on.

XML
<Window x:Class="DockPanelSplitterDemo.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:osc="clr-namespace:OpenSourceControls"
    Title="DockPanelSplitter demo" Height="400" Width="600">
    <DockPanel>
        <Grid Name="LeftPane" DockPanel.Dock="Left" 
                      Width="200" MinWidth="40">
            <Rectangle Fill="LightBlue"/>
        </Grid>
        <osc:DockPanelSplitter DockPanel.Dock="Left" Width="4"/>
 
        <Grid Name="RightPane" DockPanel.Dock="Right" Width="80">
            <Rectangle Fill="Yellow"/>
        </Grid>
        <osc:DockPanelSplitter DockPanel.Dock="Right" Width="4"/>
        
        <Grid Name="TopPane" DockPanel.Dock="Top" 
                     Height="80" MinHeight="20">
            <Rectangle Fill="LightGreen"/>
        </Grid>
        <osc:DockPanelSplitter DockPanel.Dock="Top" Height="4"/>
        
        <Grid Name="BottomPane" DockPanel.Dock="Bottom" Height="70">
            <Rectangle Fill="LightPink"/>
        </Grid>
        <osc:DockPanelSplitter DockPanel.Dock="Bottom" Height="4"/>
        
        <Grid Name="MainPane" Background="Coral" >
            <Rectangle Fill="Coral"/>
        </Grid>
    </DockPanel>
</Window>

The proportional sizing mode can be turned off by setting the ProprtionalResize dependency property to False.

XML
<osc:DockPanelSplitter DockPanel.Dock="Right" Width="4" ProportionalResize="False"/>

Links to Related Projects

  • WpfContrib DockSplitter (cannot find the control in ProportionalResize dependency property to False. Creating resizable panels with splitter bars (links don't work??)
  • Thumb example

Future Enhancements

  • Use the Thumb control instead of capturing mouse events

History

  • March 21, 2009 - First post
  • May 25, 2009 - Added proportional resizing
  • August 09, 2009 - Changed to custom control, added template demo, constrained size on client area

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Norway Norway
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionWhy do the panels behave differentlyh? Pin
Dominick Marciano7-Feb-17 4:51
professionalDominick Marciano7-Feb-17 4:51 
GeneralVery helpfull control - thank you! Pin
Member 99136139-May-14 8:42
Member 99136139-May-14 8:42 
QuestionNameSpace Error Pin
Surajit T. Karmakar6-Nov-13 19:24
professionalSurajit T. Karmakar6-Nov-13 19:24 
SuggestionSuggestion For Expanders Pin
c_manboy6-Oct-13 13:53
c_manboy6-Oct-13 13:53 
QuestionExcellent control Pin
rquintalr27-May-13 3:15
rquintalr27-May-13 3:15 
GeneralMy vote of 5 Pin
Preev21-Mar-12 13:17
Preev21-Mar-12 13:17 
GeneralMy vote of 5 Pin
napnit10-Nov-11 1:11
napnit10-Nov-11 1:11 
QuestionHow to collapse one side, the other side, or both sides of the DockPanelSplitter control? Pin
CalvinDale27-Sep-11 8:55
CalvinDale27-Sep-11 8:55 
AnswerRe: How to collapse one side, the other side, or both sides of the DockPanelSplitter control? Pin
objo29-Sep-11 20:32
objo29-Sep-11 20:32 
GeneralMy vote of 5 Pin
ferahl28-Apr-11 6:45
ferahl28-Apr-11 6:45 
Generalsilverlight Pin
joe brockhaus1-Nov-10 10:50
joe brockhaus1-Nov-10 10:50 
GeneralRe: silverlight Pin
daniel Moody17-Jul-12 9:58
daniel Moody17-Jul-12 9:58 
Modified to run under silverlight, but it still need work.

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace Silverlight3dLib1
{
public partial class DockPanelSplitter2 : UserControl
{


//!//static DockPanelSplitter2()
//!//{


//!!//DefaultStyleKeyProperty.OverrideMetadata(typeof(DockPanelSplitter),
//!!// new FrameworkPropertyMetadata(typeof(DockPanelSplitter)));


// override the Background property
//!// BackgroundProperty.OverrideMetadata(typeof(DockPanelSplitter), new FrameworkPropertyMetadata(Brushes.Transparent));

// override the Dock property to get notifications when Dock is changed
//!// DockPanel.DockProperty.OverrideMetadata(typeof(DockPanelSplitter),
//!// new FrameworkPropertyMetadata(Dock.Left, new PropertyChangedCallback(DockChanged)));
//!//}

///
/// Resize the target element proportionally with the parent container
/// Set to false if you don't want the element to be resized when the parent is resized.
///

public bool ProportionalResize
{
get { return (bool)GetValue(ProportionalResizeProperty); }
set { SetValue(ProportionalResizeProperty, value); }
}

public static readonly DependencyProperty ProportionalResizeProperty =
DependencyProperty.Register("ProportionalResize", typeof(bool), typeof(DockPanelSplitter2),
new PropertyMetadata(true));

///
/// Height or width of splitter, depends of orientation of the splitter
///

public double Thickness
{
get { return (double)GetValue(ThicknessProperty); }
set { SetValue(ThicknessProperty, value); }
}

public static readonly DependencyProperty ThicknessProperty =
DependencyProperty.Register("Thickness", typeof(double), typeof(DockPanelSplitter2),
new PropertyMetadata(4.0, ThicknessChanged));


#region Private fields
private FrameworkElement element; // element to resize (target element)
private double width; // current desired width of the element, can be less than minwidth
private double height; // current desired height of the element, can be less than minheight
private double previousParentWidth; // current width of parent element, used for proportional resize
private double previousParentHeight; // current height of parent element, used for proportional resize
#endregion

public DockPanelSplitter2()
{
Loaded += DockPanelSplitterLoaded;
Unloaded += DockPanelSplitterUnloaded;

UpdateHeightOrWidth();




}

void DockPanelSplitterLoaded(object sender, RoutedEventArgs e)
{
Panel dp = Parent as Panel;
if (dp == null) return;

// Subscribe to the parent's size changed event
dp.SizeChanged += ParentSizeChanged;

// Store the current size of the parent DockPanel
previousParentWidth = dp.ActualWidth;
previousParentHeight = dp.ActualHeight;

// Find the target element
UpdateTargetElement();

}

void DockPanelSplitterUnloaded(object sender, RoutedEventArgs e)
{
Panel dp = Parent as Panel;
if (dp == null) return;

// Unsubscribe
dp.SizeChanged -= ParentSizeChanged;
}

private static void DockChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((DockPanelSplitter2)d).UpdateHeightOrWidth();
}

private static void ThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((DockPanelSplitter2)d).UpdateHeightOrWidth();
}

private void UpdateHeightOrWidth()
{
if (IsHorizontal)
{
Height = Thickness;
Width = double.NaN;
}
else
{
Width = Thickness;
Height = double.NaN;
}
}

public bool IsHorizontal
{
get
{
Dock dock = DockPanel.GetDock(this);
return dock == Dock.Top || dock == Dock.Bottom;
}
}

///
/// Update the target element (the element the DockPanelSplitter works on)
///

private void UpdateTargetElement()
{
Panel dp = Parent as Panel;
if (dp == null) return;

int i = dp.Children.IndexOf(this);

// The splitter cannot be the first child of the parent DockPanel
// The splitter works on the 'older' sibling
if (i > 0 && dp.Children.Count > 0)
{
element = dp.Children[i - 1] as FrameworkElement;
}
}

private void SetTargetWidth(double newWidth)
{
if (newWidth < element.MinWidth)
newWidth = element.MinWidth;
if (newWidth > element.MaxWidth)
newWidth = element.MaxWidth;

// todo - constrain the width of the element to the available client area
Panel dp = Parent as Panel;
Dock dock = DockPanel.GetDock(this);
//!// MatrixTransform t = element.TransformToAncestor(dp) as MatrixTransform;
//!// if (dock == Dock.Left && newWidth > dp.ActualWidth - t.Matrix.OffsetX - Thickness)
//!// newWidth = dp.ActualWidth - t.Matrix.OffsetX - Thickness;

element.Width = newWidth;
}

private void SetTargetHeight(double newHeight)
{
if (newHeight < element.MinHeight)
newHeight = element.MinHeight;
if (newHeight > element.MaxHeight)
newHeight = element.MaxHeight;

// todo - constrain the height of the element to the available client area
Panel dp = Parent as Panel;
Dock dock = DockPanel.GetDock(this);
//!//MatrixTransform t = element.TransformToAncestor(dp) as MatrixTransform;
//!//if (dock == Dock.Top && newHeight > dp.ActualHeight - t.Matrix.OffsetY - Thickness)
//!// newHeight = dp.ActualHeight - t.Matrix.OffsetY - Thickness;

element.Height = newHeight;
}

private void ParentSizeChanged(object sender, SizeChangedEventArgs e)
{
if (!ProportionalResize) return;

DockPanel dp = Parent as DockPanel;
if (dp == null) return;

double sx = dp.ActualWidth / previousParentWidth;
double sy = dp.ActualHeight / previousParentHeight;

if (!double.IsInfinity(sx))
SetTargetWidth(element.Width * sx);
if (!double.IsInfinity(sy))
SetTargetHeight(element.Height * sy);

previousParentWidth = dp.ActualWidth;
previousParentHeight = dp.ActualHeight;

}

double AdjustWidth(double dx, Dock dock)
{
if (dock == Dock.Right)
dx = -dx;

width += dx;
SetTargetWidth(width);

return dx;
}

double AdjustHeight(double dy, Dock dock)
{
if (dock == Dock.Bottom)
dy = -dy;

height += dy;
SetTargetHeight(height);

return dy;
}

Point StartDragPoint;

protected override void OnMouseEnter(MouseEventArgs e)
{
base.OnMouseEnter(e);

if (!IsEnabled) return;
Cursor = IsHorizontal ? Cursors.SizeNS : Cursors.SizeWE;
}

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
if (!IsEnabled) return;

if (!IsMouseCaptured)
{
StartDragPoint = e.GetPosition(Parent as UIElement);
UpdateTargetElement();
if (element != null)
{
width = element.ActualWidth;
height = element.ActualHeight;
IsMouseCaptured = true;
CaptureMouse();
}
}

base.OnMouseLeftButtonDown(e);
}

private Boolean IsMouseCaptured = false;

protected override void OnMouseMove(MouseEventArgs e)
{
if (IsMouseCaptured)
{



Point ptCurrent = e.GetPosition(Parent as UIElement);
Point delta = new Point(ptCurrent.X - StartDragPoint.X, ptCurrent.Y - StartDragPoint.Y);
Dock dock = DockPanel.GetDock(this);

if (IsHorizontal)
delta.Y = AdjustHeight(delta.Y, dock);
else
delta.X = AdjustWidth(delta.X, dock);

bool isBottomOrRight = (dock == Dock.Right || dock == Dock.Bottom);

// When docked to the bottom or right, the position has changed after adjusting the size
if (isBottomOrRight)
StartDragPoint = e.GetPosition(Parent as UIElement);
else
StartDragPoint = new Point(StartDragPoint.X + delta.X, StartDragPoint.Y + delta.Y);
}
base.OnMouseMove(e);
}

protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
{
if (IsMouseCaptured)
{
IsMouseCaptured = false;
ReleaseMouseCapture();
}

base.OnMouseLeftButtonUp(e);
}
}

}
GeneralSplitter movement restriction Pin
Prasoon Chaudhary29-Apr-10 9:06
Prasoon Chaudhary29-Apr-10 9:06 
GeneralSystem.ArgumentException was unhandled Pin
kiol28-Jan-10 22:40
kiol28-Jan-10 22:40 
GeneralRe: System.ArgumentException was unhandled Pin
objo2-Feb-10 4:29
objo2-Feb-10 4:29 
GeneralRe: System.ArgumentException was unhandled Pin
HHick1234512-May-10 1:42
HHick1234512-May-10 1:42 
GeneralCode Behind Pin
Jason McPeak15-Dec-09 3:41
Jason McPeak15-Dec-09 3:41 
GeneralRe: Code Behind Pin
Jason McPeak15-Dec-09 4:39
Jason McPeak15-Dec-09 4:39 
AnswerRe: Code Behind Pin
objo15-Dec-09 4:53
objo15-Dec-09 4:53 
NewsRe: Code Behind Pin
Jason McPeak15-Dec-09 5:05
Jason McPeak15-Dec-09 5:05 
GeneralRe: Code Behind Pin
Jason McPeak15-Dec-09 5:44
Jason McPeak15-Dec-09 5:44 
GeneralRe: Code Behind Pin
Jason McPeak15-Dec-09 5:58
Jason McPeak15-Dec-09 5:58 
GeneralWell done! Pin
brents11-Dec-09 14:25
brents11-Dec-09 14:25 
GeneralTo add this code to your own assembly... Pin
SerialHobbyist17-Aug-09 3:02
SerialHobbyist17-Aug-09 3:02 
AnswerRe: To add this code to your own assembly... Pin
objo17-Aug-09 6:33
objo17-Aug-09 6:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.