防止包装TextBlock影响布局

时间:2013-10-12 17:46:14

标签: c# wpf validation textblock textwrapping

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

Current validation template

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

Desired validation template

这是产生第一个布局的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换行?

1 个答案:

答案 0 :(得分:0)

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

我想到了使用绑定来强制this帖子TextBlock的宽度。

就我而言,将TextBlock的宽度绑定到ActualWidth元素的AdornedElementPlaceholder就可以了:

<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>

最终产品:

enter image description here