These answers didn't work for me, because I needed a TextBox
to stretch (i.e. consume all available space) until it reaches it's MaxWidth
and, if more space is available, align to the right.
I created this simple control that works along the lines of Y C's answer, but doesn't require System.Windows.Interactivity
:
public class StretchAlignmentPanel : ContentControl
{
public StretchAlignmentPanel()
{
this.SizeChanged += StretchAlignmentPanel_SizeChanged;
}
public static readonly DependencyProperty HorizontalFallbackAlignmentProperty = DependencyProperty.Register(
nameof(HorizontalFallbackAlignment), typeof(HorizontalAlignment), typeof(StretchAlignmentPanel), new PropertyMetadata(HorizontalAlignment.Stretch));
public HorizontalAlignment HorizontalFallbackAlignment
{
get { return (HorizontalAlignment)GetValue(HorizontalFallbackAlignmentProperty); }
set { SetValue(HorizontalFallbackAlignmentProperty, value); }
}
public static readonly DependencyProperty VerticalFallbackAlignmentProperty = DependencyProperty.Register(
nameof(VerticalFallbackAlignment), typeof(VerticalAlignment), typeof(StretchAlignmentPanel), new PropertyMetadata(VerticalAlignment.Stretch));
public VerticalAlignment VerticalFallbackAlignment
{
get { return (VerticalAlignment)GetValue(VerticalFallbackAlignmentProperty); }
set { SetValue(VerticalFallbackAlignmentProperty, value); }
}
private void StretchAlignmentPanel_SizeChanged(object sender, System.Windows.SizeChangedEventArgs e)
{
var fe = this.Content as FrameworkElement;
if (fe == null) return;
if(e.WidthChanged) applyHorizontalAlignment(fe);
if(e.HeightChanged) applyVerticalAlignment(fe);
}
private void applyHorizontalAlignment(FrameworkElement fe)
{
if (HorizontalFallbackAlignment == HorizontalAlignment.Stretch) return;
if (this.ActualWidth > fe.MaxWidth)
{
fe.HorizontalAlignment = HorizontalFallbackAlignment;
fe.Width = fe.MaxWidth;
}
else
{
fe.HorizontalAlignment = HorizontalAlignment.Stretch;
fe.Width = double.NaN;
}
}
private void applyVerticalAlignment(FrameworkElement fe)
{
if (VerticalFallbackAlignment == VerticalAlignment.Stretch) return;
if (this.ActualHeight > fe.MaxHeight)
{
fe.VerticalAlignment = VerticalFallbackAlignment;
fe.Height= fe.MaxHeight;
}
else
{
fe.VerticalAlignment = VerticalAlignment.Stretch;
fe.Height= double.NaN;
}
}
}
It can be used like this:
<controls:StretchAlignmentPanel HorizontalFallbackAlignment="Right">
<TextBox MaxWidth="200" MinWidth="100" Text="Example"/>
</controls:StretchAlignmentPanel>