Skip to content

Instantly share code, notes, and snippets.

@xmedeko
Last active December 22, 2016 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmedeko/2ccba5649bbfb4bf5d1c5183910e0378 to your computer and use it in GitHub Desktop.
Save xmedeko/2ccba5649bbfb4bf5d1c5183910e0378 to your computer and use it in GitHub Desktop.
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