添加TextDecoration對象TextBlock.TextDecorations集合中點擊事件(例如):
XAML:
<Button Click="Button_Click_1">
<TextBlock>
Book 1
</TextBlock>
</Button>
和Handler:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
// ... your logic
var button = (Button)sender;
var textBlock = (TextBlock)button.Content;
// if decoration wasn't already inserted
//
if (!textBlock.TextDecorations.Any())
textBlock.TextDecorations.Add(new TextDecoration { Location = TextDecorationLocation.Strikethrough });
}
更新:答案的評論 - 最簡單的方法
XAML
<Button x:Name="button1" Click="Button_Click_1">
<TextBlock>
Book 1
</TextBlock>
</Button>
<Button x:Name="button2" Click="Button_Click_2">
<TextBlock>
Book 2
</TextBlock>
</Button>
代碼:
private void SetStrikethrough(Button b, Boolean strikethrough)
{
var textBlock = (TextBlock)b.Content;
if (strikethrough)
{
if (!textBlock.TextDecorations.Any())
textBlock.TextDecorations.Add(
new TextDecoration { Location = TextDecorationLocation.Strikethrough });
}
else
{
textBlock.TextDecorations.Clear();
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
SetStrikethrough(button1, true);
SetStrikethrough(button2, false);
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
var button = (Button)sender;
SetStrikethrough(button2, true);
SetStrikethrough(button1, false);
}
注意,該代碼總是假定一個按鈕含量一個文本塊。只是爲了簡單。
這就是我想要做的。但是,如果我點擊第二個按鈕(Book2),也會比「刪除線」保留在按鈕1(Book1)中。 – Georg
您的所有按鈕或不同的按鈕上都有一個事件處理程序(每個按鈕有一個)? – acrilige
我首先嚐試了所有按鈕的Button_Click_1。比我爲每個按鈕創建了2個更多。如果我點擊按鈕,刪除線不會從先前點擊的按鈕中消失 – Georg