I basically have a setup like this:
<GroupBox>
<TextBlock Name="tbValue"/>
</GroupBox>
The content of the TextBlock changes very often (displaying a measure value from a sensor). This leads to the width of the groupbox changing all the time which looks&feels like crap.
Does anyone have an idea how i could make the groupbox grow automatically when the text changes, but not shink again whenever the text gets shorter again?
Can propose behavior. Raw sample
public class GrowOnlyWidthBehavior : Behavior<FrameworkElement>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SizeChanged += OnSizeChanged;
}
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
AssociatedObject.MinWidth = Math.Max(AssociatedObject.MinWidth, AssociatedObject.ActualWidth);
}
}
Updated behavior. Thanks to AndrewS for pointing to the error in previous code. I used logic from HighCore 's answer.
Just handle the SizeChanged
event and set the GroupBox
's MinWidth
property to the largest between the MinWidth
and the ActualWidth
:
<GroupBox SizeChanged="GroupBox_SizeChanged">
<TextBlock Name="tbValue"/>
</GroupBox>
Code behind:
private void GroupBox_SizeChanged(object sender, SizeChangedEventArgs e)
{
var gb = sender as GroupBox;
gb.MinWidth = Math.Max(gb.MinWidth, gb.ActualWidth);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.