2014-04-21 60 views
-1

我正在嘗試RoutedEvent來自WPF 4的例子Unleashed book。該示例在Window上有許多控件,並且它在窗口上定義了MouseRightButtonDown以在窗口的標題欄中顯示事件源。 所以當我們右鍵單擊窗口的任何子元素時,它的名稱,類型等都顯示在窗口的標題欄中。但是,當我右鍵單擊ListBox的ListItem時,它不會在窗口的標題欄中設置它的名稱,標題等。爲什麼?爲什麼WPF ListBox.ListItems不會引發MouseRightButtonDown

的代碼如下:

XAML

<Window x:Class="TempWPFProj.RoutedEventDemo" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="About WPF 4 Unleashed" 
     SizeToContent="WidthAndHeight" 
     Background="OrangeRed" MouseRightButtonDown="Window_MouseRightButtonDown"> 
    <StackPanel> 
     <Label FontWeight="Bold" FontSize="20" Foreground="White"> 
      WPF 4 Unleashed 
     </Label> 
     <Label>© 2010 SAMS Publishing</Label> 
     <Label>Installed Chapters:</Label> 
     <ListBox> 
      <ListBoxItem>Chapter 1</ListBoxItem> 
      <ListBoxItem>Chapter 2</ListBoxItem> 
     </ListBox> 
     <StackPanel Orientation="Horizontal" HorizontalAlignment="Center"> 
      <Button MinWidth="75" Margin="10">Help</Button> 
      <Button MinWidth="75" Margin="10">OK</Button> 
     </StackPanel> 
     <StatusBar>You have successfully registered this product.</StatusBar> 
    </StackPanel> 
</Window> 

代碼隱藏CS文件

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Data; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Imaging; 
using System.Windows.Shapes; 

namespace TempWPFProj 
{ 
    /// <summary> 
    /// Interaction logic for RoutedEventDemo.xaml 
    /// </summary> 
    public partial class RoutedEventDemo : Window 
    { 
     public RoutedEventDemo() 
     { 
      InitializeComponent(); 
     } 

     private void Window_MouseRightButtonDown(object sender, MouseButtonEventArgs e) 
     { 
      // Display information about this event 
      this.Title = "Source = " + e.Source.GetType().Name + ", OriginalSource = " + 
      e.OriginalSource.GetType().Name + " @ " + e.Timestamp; 
      // In this example, all possible sources derive from Control 
      Control source = e.Source as Control; 
      // Toggle the border on the source control 
      if (source.BorderThickness != new Thickness(5)) 
      { 
       source.BorderThickness = new Thickness(5); 
       source.BorderBrush = Brushes.Black; 
      } 
      else 
       source.BorderThickness = new Thickness(0); 
     } 
    } 
} 
+0

嘗試'PreviewMouseRightButtonDown' –

回答

1

它說,就在這本書爲什麼在列表框中沒有爲工作點擊右鍵

「當您右鍵單擊任一ListBoxItem時,窗口永遠不會收到MouseRightButtonDown事件。這是因爲ListBoxItem的內部處理這一事件以及MouseLeftButtonDown事件(停止冒泡)實施項目選擇」

Link to page here

+0

你的意思'ListBoxItem'集'e.Handled = TRUE。 '在其事件處理程序內停止冒泡? – Mahesha999

相關問題