Skip to content

Instantly share code, notes, and snippets.

@xmedeko

xmedeko/Example.xaml

Last active Dec 22, 2016
Embed
What would you like to do?
WPF Content control ignoring the content width. Suitable to force a TextBlock to wrap the text.
<!-- Especially usefull when placed inside Window and ScrollViewer -->
<myc:IgnoreWidthControl>
<TextBlock Text="Very long text which has to be wrapped. Yeah, it must be wrapped." TextWrapping="Wrap" />
</myc:IgnoreWidthControl>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace MyControls
{
/// <summary>
/// Content control ignoring the content width and setting the content MaxWidth to the actual width.
/// Suitable to force a TextBlock to wrap the text.
/// </summary>
public class IgnoreWidthControl : ContentControl
{
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
if (sizeInfo.WidthChanged)
InvalidateMeasure();
}
protected override Size MeasureOverride(Size constraint)
{
constraint.Width = ActualWidth;
Size size = new Size();
UIElement child = GetFirstVisualChild();
if (child != null)
{
child.Measure(constraint);
size.Height = child.DesiredSize.Height;
}
return size;
}
private UIElement GetFirstVisualChild()
{
if (this.VisualChildrenCount <= 0)
return null;
return this.GetVisualChild(0) as UIElement;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.