这些答案对我没用,因为我需要一个 TextBox
来拉伸(即占用所有可用空间),直到达到它的 MaxWidth
,如果有更多的空间可用,则对齐到右侧。
我创建了这个简单的控件,它的工作原理类似于Y C的答案,但不需要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;
}
}
}
它可以这样使用:
<controls:StretchAlignmentPanel HorizontalFallbackAlignment="Right">
<TextBox MaxWidth="200" MinWidth="100" Text="Example"/>
</controls:StretchAlignmentPanel>