我想在自定义TextDecorations.Strikethrough
中添加RichTextBox
装饰按钮我正在使用以下代码添加和删除TextDecoration
我得到的InvalidCastException: Unable to cast object of type 'MS.Internal.NamedObject' to type 'System.Windows.TextDecorationCollection'.
{{1}当我选择的范围大于被击穿的范围并点击" StrikeThrough"按钮。
我的代码
private void StrikeOutButton_Click(object sender, RoutedEventArgs e)
{
TextRange range = new TextRange(this.MyRichTextBox.Selection.Start,
this.MyRichTextBox.Selection.End);
TextDecorationCollection tdc =
(TextDecorationCollection)this.MyRichTextBox.
Selection.GetPropertyValue(Inline.TextDecorationsProperty);
/*
if (tdc == null || !tdc.Equals(TextDecorations.Strikethrough))
{
tdc = TextDecorations.Strikethrough;
}
else
{
tdc = new TextDecorationCollection();
}
* */
if (tdc == null || !tdc.Contains(TextDecorations.Strikethrough[0]))
{
tdc = TextDecorations.Strikethrough;
}
else
{
tdc = new TextDecorationCollection();
}
range.ApplyPropertyValue(Inline.TextDecorationsProperty, tdc);
}
注释掉代码也无效。
我打算发布ExceptionDetails,但我认为它非常清楚。
有人可以为我提供解决方法吗?
答案 0 :(得分:1)
问题在于,如果您的完整文字未使用删除线进行修饰,您将获得DependencyProperty.UnsetValue
。
因此,您可以检查DependencyProperty.UnsetValue
并在这种情况下仅应用删除线。
我做了一个简短的测试,这个解决方案适合我:
private void StrikeOutButton_Click(object sender, RoutedEventArgs e)
{
TextRange textRange = new TextRange(TextBox.Selection.Start, TextBox.Selection.End);
var currentTextDecoration = textRange.GetPropertyValue(Inline.TextDecorationsProperty);
TextDecorationCollection newTextDecoration;
if (currentTextDecoration != DependencyProperty.UnsetValue)
newTextDecoration = ((TextDecorationCollection)currentTextDecoration == TextDecorations.Strikethrough) ? new TextDecorationCollection() : TextDecorations.Strikethrough;
else
newTextDecoration = TextDecorations.Strikethrough;
textRange.ApplyPropertyValue(Inline.TextDecorationsProperty, newTextDecoration);
}