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