Last active
June 3, 2024 08:27
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- 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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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