以编程方式从WPF中的代码中删除Strikethrough TextDecoration

Ber*_* L. 3 .net c# wpf

我在WPF桌面应用程序中遇到以下问题时遇到问题:

我从后面的代码动态创建TextBlocks并将它们插入到StackPanel中.这项工作到目前为止.当用户将鼠标移到TextBlock上时,Strikthrough将应用于文本块,表示可以通过单击删除该项目.同样,这仍然有效.当鼠标离开文本块时,删除删除线,这里抛出异常,说IsFrozen必须设置为false才能更改TextDecorationCollection对象.我无法弄清楚如何解决这个问题.

这是我的代码:

private void HandleAddedSecondaryDxMouseEnter(Object sender, MouseEventArgs e) {
    TextBlock tbl = (TextBlock)sender;
    tbl.TextDecorations = TextDecorations.Strikethrough;
}

private void HandleAddedSecondaryDxMouseLeave(Object sender, MouseEventArgs e) {
    TextBlock tbl = (TextBlock)sender;
    tbl.TextDecorations.Remove(tbl.TextDecorations[0]);
}
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激.

谢谢,伯恩德

小智 7

我发现以下内容最适合我:

TextDecorationCollection decs = (TextDecorationCollection)theRTB.Selection.GetPropertyValue( Inline.TextDecorationsProperty );
if (decs.Contains(TextDecorations.Underline[0]))
{
    TextDecorationCollection noUnder = new TextDecorationCollection(decs);
    noUnder.Remove(TextDecorations.Underline[0]);  //this is a bool, and could replace Contains above
    theRTB.Selection.ApplyPropertyValue(Inline.TextDecorationsProperty, noUnder);
}
Run Code Online (Sandbox Code Playgroud)

显然这是为了删除下划线装饰,但我认为删除线也没有什么不同.

  • 这应该是答案. (3认同)

sa_*_*213 5

你可以设置TextDecorations为null,这将清除Strikethrough装饰TextBlock

private void HandleAddedSecondaryDxMouseLeave(Object sender, MouseEventArgs e)
{
    TextBlock tbl = (TextBlock)sender;
    tbl.TextDecorations = null;
}
Run Code Online (Sandbox Code Playgroud)