【问题标题】:Prevent wrapping TextBlock from affecting layout防止包装 TextBlock 影响布局
【发布时间】:2013-10-12 17:46:13
【问题描述】:

我曾多次遇到此问题,但尚未找到简单的解决方案。当TextBlock(带有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 换行吗?

【问题讨论】:

    标签: c# wpf validation textblock word-wrap


    【解决方案1】:

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

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

    在我的例子中,将TextBlock 的宽度绑定到AdornedElementPlaceholder 元素的ActualWidth 做到了:

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

    最终产品:

    【讨论】:

    • 正是我想要的,谢谢!我只尝试了宽度属性,但也需要高度。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2014-01-15
    相关资源
    最近更新 更多