2010-11-11 10 views
3

有沒有一種方法,我可以實現在ListBoxItemClick?有MouseLeftButtonUp,但它不是真的一樣,我可以將鼠標放在其他地方,並拖動到另一個ListBoxItem,它仍然有效,小問題壽,它也許怪異用戶壽如何在ListBoxItem上有Click事件?

+0

這是在這裏回答:http://stackoverflow.com/a/821609/58768 – 2013-05-15 12:18:40

回答

2

你可以做一個新的ControlTemplate與東西ListBoxItem中可點擊作爲根元素(如Button),處理點擊事件並將ContentPresenter放置在「可點擊」內?

+0

我想這是1解決方案,我只是等待,看看是否有其他解決方案,否則這將被標記爲答案 – 2010-11-11 07:48:23

3

我刪除了這個答案,因爲我意識到,這是辦法不多於這個簡單的任務,但後來我想無論如何,我會發布它,以防有人想知道如何繼承ListBoxItem中因任何原因。

要真正擺脫你必須做到以下幾點一ListBoxItem的Click事件。第一個子類ListBoxItem並檢查MouseEnter,MouseLeave,MouseUp,MouseDown以知道何時觸發它。

public class ClickableListBoxItem : ListBoxItem 
{ 
    // Register the routed event 
    public static readonly RoutedEvent ClickEvent = 
     EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, 
     typeof(RoutedEventHandler), typeof(ClickableListBoxItem)); 

    // .NET wrapper 
    public event RoutedEventHandler Click 
    { 
     add 
     { 
      AddHandler(ClickEvent, value); 
     } 
     remove 
     { 
      RemoveHandler(ClickEvent, value); 
     } 
    } 

    protected void OnClick() 
    { 
     RaiseEvent(new RoutedEventArgs(ClickEvent)); 
    } 

    private bool m_isClickable = false; 
    private bool m_click = false; 
    protected override void OnMouseEnter(System.Windows.Input.MouseEventArgs e) 
    { 
     m_isClickable = true; 
     base.OnMouseEnter(e); 
    } 
    protected override void OnMouseLeave(System.Windows.Input.MouseEventArgs e) 
    { 
     m_isClickable = false; 
     base.OnMouseLeave(e); 
    } 
    protected override void OnPreviewMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e) 
    { 
     if (m_click == true) 
     { 
      OnClick(); 
     } 
     base.OnPreviewMouseLeftButtonUp(e); 
    } 
    protected override void OnPreviewMouseLeftButtonDown(System.Windows.Input.MouseButtonEventArgs e) 
    { 
     if (m_isClickable == true) 
     { 
      m_click = true; 
     } 
     base.OnPreviewMouseLeftButtonDown(e); 
    } 
} 

要獲得ListBox中使用ClickableListBoxItem,而不是一個ListBoxItem我們也必須繼承ListBox和重寫GetContainerForItemOverride。

public class ClickableListBox : ListBox 
{ 
    protected override DependencyObject GetContainerForItemOverride() 
    { 
     //Use our own ListBoxItem 
     return new ClickableListBoxItem(); 
    } 
} 

然後我們可以在Xaml中使用這個ClickableListBox並獲得像這樣的Click事件。這將工作沒有馬瑟您在ItemTemplate放什麼,按鈕,文本框的TextBlocks等

<local:ClickableListBox x:Name="c_listBox"> 
    <local:ClickableListBox.ItemContainerStyle> 
     <Style TargetType="{x:Type local:ClickableListBoxItem}"> 
      <EventSetter Event="Click" Handler="ListBoxItem_Click"/> 
     </Style> 
    </local:ClickableListBox.ItemContainerStyle> 
</local:ClickableListBox> 

更簡單的解決辦法是隻要繼承在ItemTemplate爲ListBoxItem的父容器,並使用相同的鼠標的程序。