2013-05-10 64 views
2

我必須實現以下行爲在我的WPF桌面應用程序的問題:編程方式從代碼中刪除刪除線TextDecoration落後於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]); 
} 

任何幫助將不勝感激。

感謝, 貝恩德

+2

你可以將其設置爲'null','tbl.TextDecorations = NULL;' – 2013-05-10 10:39:51

+0

大,是沒有的伎倆!非常感謝! – 2013-05-10 10:55:59

+2

如果上面的評論做了你想做的事情,你可能想要回答並關閉這個問題 – Arj 2013-05-10 11:11:06

回答

3

您可以設置TextDecorationsnull,這將清除Strikethrough裝飾從TextBlock

private void HandleAddedSecondaryDxMouseLeave(Object sender, MouseEventArgs e) 
{ 
    TextBlock tbl = (TextBlock)sender; 
    tbl.TextDecorations = null; 
} 
6

我發現下面的工作最適合我:

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); 
} 

顯然這是去除下劃線的裝飾,但我想象刪除線將沒有什麼不同。

+1

This應該是答案。 – 2017-03-02 01:44:19

+0

謝謝。我一直在尋找這個。 – 2017-07-20 02:55:11

0

我已經使用下面的代碼來刪除文本範圍的下劃線。對於TextBlock也一樣。

TextDecorationCollection textDecorations; 
(textRange.GetPropertyValue(Inline.TextDecorationsProperty) as TextDecorationCollection).TryRemove(TextDecorations.Underline, out textDecorations); 
textRange.ApplyPropertyValue(Inline.TextDecorationsProperty, textDecorations);