1

我已经多次遇到这个问题,但还没有找到一个简单的解决方案。当 a TextBlock(with TextWrapping="Wrap") 嵌入到另一个未指定其宽度的元素中时,它TextBlock会扩展到其父级允许的大小,而不是首先尝试包装其文本。例如,我目前正在开发一个TextBlock ValidationTemplate. 以下是模板当前如何处理超过宽度的文本TextBox

当前验证模板

这显然不是最优的。这是我希望它出现的方式:

所需的验证模板

ControlTemplate这是生成第一个布局的 XAML :

<ControlTemplate>
  <DockPanel LastChildFill="True">
    <Border DockPanel.Dock="Top" BorderBrush="Red" BorderThickness="1">
      <DockPanel>
        <AdornedElementPlaceholder x:Name="TargetTextBox" />
        <Grid x:Name="WarningBoxContainer" Background="Red" Width="{Binding ElementName=TargetTextBox, Path=ActualHeight}" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}">
            <Path Margin="5" Stretch="Fill" Fill="#FFFFFFFF" Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z "/>
        </Grid>
      </DockPanel>
    </Border>
    <Border DockPanel.Dock="Top" Margin="0,2,0,0">
      <TextBlock Text="Something very terrible has happened" TextWrapping="Wrap"/>
    </Border>
  </DockPanel>
</ControlTemplate>

有谁知道TextBlock在尝试扩展之前如何进行包装?

4

1 回答 1

1

当然,在我发帖几分钟后,我找到了答案。

TextBlock这篇文章中得到了使用绑定来强制宽度的想法。

TextBlock在我的例子中,将's 的宽度绑定ActualWidthAdornedElementPlaceholder元素的 ' 做到了:

<ControlTemplate>
  <DockPanel LastChildFill="True">
    <Border DockPanel.Dock="Top" BorderBrush="Red" BorderThickness="1">
      <DockPanel>
        <AdornedElementPlaceholder x:Name="TargetTextBox" />
        <Grid x:Name="WarningBoxContainer" Background="Red" Width="{Binding ElementName=TargetTextBox, Path=ActualHeight}" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}">
            <Path Margin="5" Stretch="Fill" Fill="#FFFFFFFF" Data="F1 M 26.9166,22.1667L 37.9999,33.25L 49.0832,22.1668L 53.8332,26.9168L 42.7499,38L 53.8332,49.0834L 49.0833,53.8334L 37.9999,42.75L 26.9166,53.8334L 22.1666,49.0833L 33.25,38L 22.1667,26.9167L 26.9166,22.1667 Z "/>
        </Grid>
      </DockPanel>
    </Border>
    <Border DockPanel.Dock="Top" Margin="0,2,0,0">
      <TextBlock Text="Something very terrible has happened" TextWrapping="Wrap" HorizontalAlignment="Left" Width="{Binding ElementName=TargetTextBox, Path=ActualWidth}" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}"/>
    </Border>
  </DockPanel>
</ControlTemplate>

最终产品:

在此处输入图像描述

于 2013-10-12T17:51:20.633 回答