Sco*_*ger 91 wpf xaml alignment stretch
这似乎应该很容易,但我很难过.在WPF中,我想要一个TextBox,它延伸到它的父级宽度,但只有最大宽度.问题是我希望它在其父级中被左对齐.要使它伸展,你必须使用HorizontalAlignment ="Stretch",但结果居中.我已经尝试过HorizontalContentAlignment,但它似乎没有做任何事情.
如何让这个蓝色文本框随窗口大小增长,最大宽度为200像素,并且左对齐?
<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>
Run Code Online (Sandbox Code Playgroud)
有什么诀窍?
Nir*_*Nir 87
您可以设置HorizontalAlignment为Left,设置您的MaxWidth,然后绑定Width到ActualWidth父元素:
<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>
Run Code Online (Sandbox Code Playgroud)
Ken*_*art 46
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MaxWidth="200"/>
</Grid.ColumnDefinitions>
<TextBox Background="Azure" Text="Hello" />
</Grid>
Run Code Online (Sandbox Code Playgroud)
两个答案都适用于我说的问题 - 谢谢!
在我的真实应用程序中,我试图限制ScrollViewer内部的一个面板,而Kent的方法由于某些原因我没有理由去追踪,因此无法很好地处理.基本上控件可能会扩展到MaxWidth设置之外并且打败了我的意图.
Nir的技术运作良好,并没有ScrollViewer的问题,尽管有一点需要注意.您希望确保TextBox上的左右边距设置为0或者它们会妨碍它们.我还更改了绑定以使用ViewportWidth而不是ActualWidth来避免出现垂直滚动条时出现问题.
您可以将其用于DataTemplate的宽度:
Width="{Binding ActualWidth,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ScrollContentPresenter}}}"
Run Code Online (Sandbox Code Playgroud)
确保您的DataTemplate根目录具有Margin ="0"(您可以使用某个面板作为根并将边距设置为该根的子节点)
| 归档时间: |
|
| 查看次数: |
96818 次 |
| 最近记录: |