2013-01-31 149 views
1

我有一個帶3個按鈕的WrapPanel。在鼠標單擊刪除線按鈕

<WrapPanel Orientation="Horizontal"> 
    <Button Content="Book1" /> 
    <Button Content="Book2" /> 
    <Button Content="Book3" /> 
</WrapPanel> 

如果我點擊Book1,我會看到Book1的內容。如果我點擊Book2,我會看到Book2的內容等。如果點擊它,是否有任何可以刪除按鈕的命令?在HTML中有「DEL」文本:

<del>Strikethrough</del> 

我想相同的,但在WPF和帶有按鈕

謝謝

回答

2

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

注意,該代碼總是假定一個按鈕含量一個文本塊。只是爲了簡單。

+0

這就是我想要做的。但是,如果我點擊第二個按鈕(Book2),也會比「刪除線」保留在按鈕1(Book1)中。 – Georg

+0

您的所有按鈕或不同的按鈕上都有一個事件處理程序(每個按鈕有一個)? – acrilige

+0

我首先嚐試了所有按鈕的Button_Click_1。比我爲每個按鈕創建了2個更多。如果我點擊按鈕,刪除線不會從先前點擊的按鈕中消失 – Georg