C# 防止换行TextBlock影响布局
我已经多次遇到这个问题,还没有找到一个简单的解决方案。当C# 防止换行TextBlock影响布局,c#,wpf,validation,textblock,word-wrap,C#,Wpf,Validation,Textblock,Word Wrap,我已经多次遇到这个问题,还没有找到一个简单的解决方案。当TextBlock(带有TextWrapping=“Wrap”)嵌入到未指定其宽度的另一个元素中时,TextBlock将扩展到其父元素允许的最大值,而不是首先尝试包装其文本。例如,我目前正在开发一个TextBlockValidationTemplate。以下是模板当前处理超过文本框宽度的文本的方式: 这显然不是最优的。下面是我希望它的外观: 下面是生成第一个布局的ControlTemplate的XAML: <ControlTemp
TextBlock
(带有TextWrapping=“Wrap”
)嵌入到未指定其宽度的另一个元素中时,TextBlock
将扩展到其父元素允许的最大值,而不是首先尝试包装其文本。例如,我目前正在开发一个TextBlock
ValidationTemplate
。以下是模板当前处理超过文本框宽度的文本的方式:
这显然不是最优的。下面是我希望它的外观:
下面是生成第一个布局的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>
有人知道如何在尝试展开前将文本块
包装起来吗?当然,在我发帖几分钟后,我找到了答案
我想到了使用绑定来强制post中TextBlock
的宽度
在我的例子中,将TextBlock
的宽度绑定到AdorneDeletePlaceholder
元素的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>
最终产品: