WPF:的Horizo​​ntalAlignment =拉伸,了maxWidth,并留在同一时间一致?Horizo、WPF、maxWidth、ntalAlignment

2023-09-11 07:32:53 作者:且醉ど且歌

这似乎应该很容易,但我难倒。在WPF中,我想一个文本框,绵延的宽度它的父,而只是一个最大宽度。问题是,我希望它是其父项内左对齐。为了得到它伸展你必须使用的Horizo​​ntalAlignment =拉伸,但随后的结果居中。我已经尝试了Horizo​​ntalContentAlignment,但它似乎并没有做任何事情。

This seems like it should be easy but I'm stumped. In WPF, I'd like a TextBox that stretches to the width of it's parent, but only to a maximum width. The problem is that I want it to be left justified within its parent. To get it to stretch you have to use HorizontalAlignment="Stretch", but then the result is centered. I've experimented with HorizontalContentAlignment, but it doesn't seem to do anything.

我如何得到这个蓝色的文本框与窗口的大小成长,有200像素的最大宽度,并且是左对齐?

How do I get this blue text box to grow with the size of the window, have a maximum width of 200 pixels, and be left justified?

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

有什么诀窍?谢谢!

What's the trick? Thanks!

推荐答案

您可以设置的Horizo​​ntalAlignment 至左,设置你的了maxWidth ,然后绑定宽度 ActualWidth的父元素:

You can set HorizontalAlignment to Left, set your MaxWidth and then bind Width to the ActualWidth of the parent element:

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