Grid 中有两个 TextBlock,一个 TextBlock 如何换行而另一个设置 Grid 宽度?

问题描述 投票:0回答:0

我有以下 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 的实际宽度?

更新 1

我可以使用这段代码让包装开始工作:

<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 被包装:

但是一旦展开就不会再收缩了

c# wpf word-wrap wpf-grid
© www.soinside.com 2019 - 2024. All rights reserved.