HorizontalAlignment = Estiramiento, maxWidth, y alineado a la izquierda al mismo tiempo?


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

¿Cómo puedo hacer que este cuadro de texto azul crezca con el tamaño de la ventana, tener un ancho máximo de 200 píxeles, y estar justificado a la izquierda?

<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?

Author: Andreas Niedermair, 2008-11-11

6 answers

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

<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>
 83
Author: Nir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-26 21:38:04
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" MaxWidth="200"/>
    </Grid.ColumnDefinitions>

    <TextBox Background="Azure" Text="Hello" />
</Grid>
 43
Author: Kent Boogaart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-28 01:05:08

Ambas respuestas dadas funcionaron para el problema que dije Thanks ¡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 manejó 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 derrotaron mi intención.

La técnica de Nir funcionó bien y no tuvo el problema con el ScrollViewer, aunque hay una cosa menor a tener en cuenta. Usted desea asegurarse de que los márgenes derecho e izquierdo en el cuadro de texto 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 aparecía la barra de desplazamiento vertical.

 8
Author: Scott Bussinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-11 11:26:27

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 de DataTemplate tenga Margin = " 0 " (puede usar algún panel como raíz y establecer el Margen a los hijos de esa raíz)

 6
Author: Filip Skakun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-26 08:25:00

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>
 0
Author: Patrick Cairns,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-03 19:50:22

Tal vez todavía pueda ayudar a alguien que se tope con esta pregunta, porque este es un tema muy antiguo.

También necesitaba esto y escribí un comportamiento para ocuparme 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 olvidar usar el espacio de nombres System.Windows.Interactivity para usar el comportamiento.

 0
Author: Y C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-19 12:44:53