Introduction
This article introduces a simple control which allows to share height and/or width between multiple instances of it. It can be used very similar to the SharedSize feature of the Grid control, but it's easier to use and it can mix shared width and height.
Background
I often have to have multiple controls on a window that needs to have the same height or width. Most of the time I used the Grid
control and
its SharedSizeScope
feature.
To do so you have to write a lot of XAML code sometimes. Specially if you want to have multiple
ItemsControl
s (like ListBox
) where for example the items should have the same row height.
This why I created the SharedSizeControl
.
The demo application show two use cases: Simple share size in a couple of
StackPanel
s and share row height over multiple ListBox
es.
Using the code
Using the control is as simple as using a Border
. You simply surround the desired controls with a SharedSizeControl
and specify the SharedWidthGroup
and/or ShredHeightGroup
property.
<sharedSize:SharedSizeControl SharedHeightGroup="HeightGroup1" SharedWidthGroup="WidthGroup1">
<Button Content="Shares width and hight"/>
</sharedSize:SharedSizeControl>
...
<sharedSize:SharedSizeControl SharedWidthGroup="WidthGroup1">
<Button Content="Shares only width"/>
</sharedSize:SharedSizeControl>
...
<sharedSize:SharedSizeControl SharedHeightGroup="HeightGroup1">
<Button Content="Shares only hight"/>
</sharedSize:SharedSizeControl>
You can define multiple shared size scopes in a window by applying the attached dependency property
IsSharedSizeScope
to any control
<Grid sharedSize:SharedSizeControl.IsSharedSizeScope="True">
...
</Grid>
How does it work
The magic is inside the MeasureOverride
method of the SharedSizeControl
:
protected override Size MeasureOverride(Size constraint)
{
var size = base.MeasureOverride(constraint);
if (String.IsNullOrEmpty(SharedWidthGroup) && String.IsNullOrEmpty(SharedHeightGroup))
{
return size;
}
var scope = GetScope();
if (!String.IsNullOrEmpty(SharedWidthGroup))
{
size.Width = scope.GetMaxSizeValue(SharedWidthGroup);
}
if (!String.IsNullOrEmpty(SharedHeightGroup))
{
size.Height = scope.GetMaxSizeValue(SharedHeightGroup);
}
return size;
}
The GetMaxSizeValue
method iterates through all controls and returns the maximum width/height of the SharedSizeControl
content.
This maximum width/height is returned as the needed size for the SharedSizeControl
.
The remaining code is mainly for managing the shared size scopes and groups.
History
2012/12/26 - Initial release.