我有以下 XAML:
<UserControl x:Class="TestWrappingWpf.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestWrappingWpf"
mc:Ignorable="d" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock TextWrapping="NoWrap">
This should not wrap
</TextBlock>
<TextBlock Grid.Row="1" TextWrapping="Wrap">
This should word wrap, but it doesn't and it stretches the StackPanel
</TextBlock>
</Grid>
</UserControl>
渲染如下图所示:
我想让第一个TextBlock设置网格的宽度,第二个TextBlock应该根据第一个TextBlock设置的宽度换行。
结果会是这样的:
如何让第二个 TextBlock 换行以响应父 Grid 的实际宽度?
我可以使用这段代码让包装开始工作:
<UserControl x:Class="TestWrappingWpf.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestWrappingWpf"
mc:Ignorable="d" >
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock x:Name="FirstTextBlock" TextWrapping="NoWrap">
This should not wrap
</TextBlock>
<TextBlock Grid.Row="1" TextWrapping="Wrap" MaxWidth="{Binding ElementName=MainGrid, Path=ActualWidth}">
This should word wrap, but it doesn't and it stretches the Grid
</TextBlock>
</Grid>
</UserControl>
不幸的是,在显示 UI 后这并没有缩小。如果我展开包装响应扩展,但如果 UI 收缩则不会包装。
这是一个更大的应用程序中的示例。最初 UI 被包装:
但是一旦展开就不会再收缩了