如何在WPF TextBlock中改变TextDecoration的颜色
本文关键字:改变 TextDecoration 颜色 TextBlock WPF | 更新日期: 2023-09-27 18:12:53
我正在改变TextDecoration
的颜色:
<Grid Background="{x:Null}"
Margin="10,0,10,0">
<TextBlock Text="{Binding Value}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Style="{StaticResource SWMRegularTextBlockStyle}"
Margin="0"
FontSize="{DynamicResource RegularFontSize}"
x:Name="tb" />
<Line VerticalAlignment="Center"
HorizontalAlignment="Center"
Visibility="{Binding InStock, Converter={StaticResource ReverseBooleanToVisiblity}}"
Stroke="Red"
Margin="0"
StrokeThickness="2"
X1="1"
Stretch="Fill"
Width="{Binding ActualWidth, ElementName=tb, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
但是当Text
有两行时,它失败了。请帮我更改TextDecoration的颜色。提前谢谢。
注意:我想要TextBlock
前景和通过线在不同的颜色。
我想这就是你要找的。
<TextBlock Text="{Binding Value}" VerticalAlignment="Center" HorizontalAlignment="Center" Style="{StaticResource SWMRegularTextBlockStyle}" Margin="0" FontSize="{DynamicResource RegularFontSize}" x:Name="tb" >
<TextBlock.TextDecorations>
<TextDecoration Location="Strikethrough">
<TextDecoration.Pen>
<Pen Brush="Red" />
</TextDecoration.Pen>
</TextDecoration>
</TextBlock.TextDecorations>
</TextBlock>
问题是你在文本上叠加了一行。当文本换行时,你需要创建另一行,这并不容易。
您可以解决这个问题,根本不使用行,而是使用特定的笔的TextDecoration的划线后面的代码。
答案在这里
private void WindowLoaded(object sender, EventArgs e)
{
// Fill the overline decoration with a solid color brush.
TextDecorationCollection myCollection = new TextDecorationCollection();
TextDecoration myStrikeThrough = new TextDecoration();
myStrikeThrough.Location = TextDecorationLocation.Strikethrough;
// Set the solid color brush.
myStrikeThrough.Pen = new Pen(Brushes.Red, 2);
myStrikeThrough.PenThicknessUnit = TextDecorationUnit.FontRecommended;
// Set the underline decoration to the text block.
myCollection.Add(myStrikeThrough);
tb.TextDecorations = myCollection;
}
然后简化XAML。删除Line控件,并将Loaded="WindowLoaded"
添加到Window