working not left content wpf xaml alignment stretch

wpf - not - HorizontalAlignment=Stretch, MaxWidth, y alineado a la izquierda al mismo tiempo?



wpf padding (6)

Parece que debería ser fácil, pero estoy perplejo. En WPF, me gustaría un TextBox que se extienda al ancho de su matriz, pero solo a un ancho máximo. El problema es que quiero que quede justificado dentro de su padre. Para que se estire, debes usar HorizontalAlignment = "Stretch", pero luego el resultado está centrado. He experimentado con HorizontalContentAlignment, pero parece que no hace nada.

¿Cómo hago para que este cuadro de texto azul crezca con el tamaño de la ventana, tenga un ancho máximo de 200 píxeles y quede justificado?

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel> <TextBox Background="Azure" Text="Hello" HorizontalAlignment="Stretch" MaxWidth="200" /> </StackPanel> </Page>

¿Cuál es el truco?


Ambas respuestas dadas funcionaron para el problema que dije: ¡Gracias!

En mi aplicación real, sin embargo, estaba tratando de restringir un panel dentro de un ScrollViewer y el método de Kent no lo manejaba muy bien por alguna razón que no me molesté en rastrear. Básicamente, los controles podrían expandirse más allá de la configuración de MaxWidth y vencer mi intento.

La técnica de Nir funcionó bien y no tuvo el problema con el ScrollViewer, aunque hay una cosa menor a tener en cuenta. Desea asegurarse de que los márgenes derecho e izquierdo en el TextBox estén configurados en 0 o se interpondrán en el camino. También cambié el enlace para usar ViewportWidth en lugar de ActualWidth para evitar problemas cuando apareció la barra de desplazamiento vertical.


Puede establecer HorizontalAlignment a la izquierda, establecer su MaxWidth y luego vincular el Width al ActualWidth del elemento principal:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel Name="Container"> <TextBox Background="Azure" Width="{Binding ElementName=Container,Path=ActualWidth}" Text="Hello" HorizontalAlignment="Left" MaxWidth="200" /> </StackPanel> </Page>


Puede usar esto para el ancho de su DataTemplate:

Width="{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}"

Asegúrese de que su raíz DataTemplate tenga Margen = "0" (puede usar algún panel como raíz y establecer el Margen para los hijos de esa raíz)


Quizás todavía pueda ayudar a alguien que se encuentre con esta pregunta, porque este es un tema muy antiguo.

Necesitaba esto también y escribí un comportamiento para encargarme de esto. Así que aquí está el comportamiento:

public class StretchMaxWidthBehavior : Behavior<FrameworkElement> { protected override void OnAttached() { base.OnAttached(); ((FrameworkElement)this.AssociatedObject.Parent).SizeChanged += this.OnSizeChanged; } protected override void OnDetaching() { base.OnDetaching(); ((FrameworkElement)this.AssociatedObject.Parent).SizeChanged -= this.OnSizeChanged; } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { this.SetAlignments(); } private void SetAlignments() { var slot = LayoutInformation.GetLayoutSlot(this.AssociatedObject); var newWidth = slot.Width; var newHeight = slot.Height; if (!double.IsInfinity(this.AssociatedObject.MaxWidth)) { if (this.AssociatedObject.MaxWidth < newWidth) { this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Left; this.AssociatedObject.Width = this.AssociatedObject.MaxWidth; } else { this.AssociatedObject.HorizontalAlignment = HorizontalAlignment.Stretch; this.AssociatedObject.Width = double.NaN; } } if (!double.IsInfinity(this.AssociatedObject.MaxHeight)) { if (this.AssociatedObject.MaxHeight < newHeight) { this.AssociatedObject.VerticalAlignment = VerticalAlignment.Top; this.AssociatedObject.Height = this.AssociatedObject.MaxHeight; } else { this.AssociatedObject.VerticalAlignment = VerticalAlignment.Stretch; this.AssociatedObject.Height = double.NaN; } } } }

Entonces puedes usarlo así:

<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="Label" /> <TextBox Grid.Column="1" MaxWidth="600"> <i:Interaction.Behaviors> <cbh:StretchMaxWidthBehavior/> </i:Interaction.Behaviors> </TextBox> </Grid>

Y finalmente, olvidarte de usar el espacio de nombres System.Windows.Interactivity para usar el comportamiento.


Yo usaría SharedGroupSize

<Grid> <Grid.ColumnDefinition> <ColumnDefinition SharedGroupSize="col1"></ColumnDefinition> <ColumnDefinition SharedGroupSize="col2"></ColumnDefinition> </Grid.ColumnDefinition> <TextBox Background="Azure" Text="Hello" Grid.Column="1" MaxWidth="200" /> </Grid>


<Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" MaxWidth="200"/> </Grid.ColumnDefinitions> <TextBox Background="Azure" Text="Hello" /> </Grid>