你可以使用这个技巧:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<WrapPanel x:Name="mywrappanel">
<TextBox Text="Text1"/>
<TextBox Text="Text2"/>
<TextBox Text="Text3"/>
<Border Width="{Binding Path=ActualWidth, ElementName=mywrappanel}"/>
<TextBox Text="Text4"/>
<TextBox Text="Text5"/>
</WrapPanel>
</Page>
它正在做的是使用一个没有高度的虚拟元素(因此它是“隐藏的”),但其宽度与WrapPanel 匹配,因此您可以确定它不适合当前行,并且“填充”下一个。
您可以使用任何FrameworkElement 派生元素作为虚拟元素...只需选择一个轻量级元素以避免不必要的内存使用。
如果您不想命名 WrapPanel,则可以使用使用 RelativeSource 的绑定,例如
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<WrapPanel x:Name="mywrappanel">
<TextBox Text="Text1"/>
<TextBox Text="Text2"/>
<TextBox Text="Text3"/>
<Border Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type WrapPanel}}}"/>
<TextBox Text="Text4"/>
<TextBox Text="Text5"/>
</WrapPanel>
</Page>
为了更好地可视化它在做什么......只需给它一个高度和一些颜色。
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<WrapPanel x:Name="mywrappanel">
<TextBox Text="Text1"/>
<TextBox Text="Text2"/>
<TextBox Text="Text3"/>
<Border Height="20" Background="Red" Width="{Binding Path=ActualWidth, ElementName=mywrappanel}"/>
<TextBox Text="Text4"/>
<TextBox Text="Text5"/>
</WrapPanel>
</Page>
如果您希望您的 XAML 更清晰/更清晰(即没有绑定和虚拟 Border),那么您可以创建自己的 FrameworkElement,它旨在始终匹配祖先 @987654332 的宽度@。
在此处查看NewLine 元素: