In the past I have done something like this by altering the ContentTemplate
of an object based on the object's size.
Typically I add an event to both the Loaded
and SizeChanged
events of the parent object, and from there figure out if the control is visible or not. If not, I change the template to a smaller version of the template.
In reference to your comment here about the SizeChanged
event not firing, that is probably because you have your objects in a StackPanel
, which will grow/shrink to fit the size of it's children, not to match the size of it's parent (the Grid
cell).
You can probably also do this using a DataTrigger
and Converter
on the actual UI object, so it automatically checks to see if the Template should changed when the control's ActualWidth
or ActualHeight
changes.
I have a helper class I use to determine the exact visibility of a UI control within it's parent object, to find out if it's fully or partially visible, or hidden entirely. The code can be found in this answer, although I'll also copy it here:
public enum ControlVisibility
{
Hidden,
Partial,
Full,
FullHeightPartialWidth,
FullWidthPartialHeight
}
/// <summary>
/// Checks to see if an object is rendered visible within a parent container
/// </summary>
/// <param name="child">UI element of child object</param>
/// <param name="parent">UI Element of parent object</param>
/// <returns>ControlVisibility Enum</returns>
public static ControlVisibility IsObjectVisibleInContainer(
FrameworkElement child, UIElement parent)
{
GeneralTransform childTransform = child.TransformToAncestor(parent);
Rect childSize = childTransform.TransformBounds(
new Rect(new Point(0, 0), new Point(child.Width, child.Height)));
Rect result = Rect.Intersect(
new Rect(new Point(0, 0), parent.RenderSize), childSize);
if (result == Rect.Empty)
{
return ControlVisibility.Hidden;
}
if (result.Height == childSize.Height && result.Width == childSize.Width)
{
return ControlVisibility.Full;
}
if (result.Height == childSize.Height)
{
return ControlVisibility.FullHeightPartialWidth;
}
if (result.Width == childSize.Width)
{
return ControlVisibility.FullWidthPartialHeight;
}
return ControlVisibility.Partial;
}
You can get a control's visibility like this:
ControlVisibility ctrlVisibility =
WPFHelpers.IsObjectVisibleInContainer(button, parent);
if (ctrlVisibility == ControlVisibility.Full
|| isVisible == ControlVisibility.FullWidthPartialHeight)
{
// Set big template
}
else
{
// Set little template
}