2011-09-22 55 views
1

我有一個DataTemplate列表框的項目。 在我的模板裏面,我有一個標籤和3個按鈕。按鈕處理MouseLeftButtonDown但仍然希望事件冒泡

我的問題是,當我點擊按鈕,listboxitem從未被選中,因爲按鈕處理事件。

有沒有辦法讓事件仍然在樹上冒泡,讓我的listboxitem變得被選中,並且仍然點擊按鈕?

+2

看到這個問題:http://stackoverflow.com/questions/662201/why-doesnt-button-click-event-bubble-up-visual-tree-to- stackpanel-as-msdn-arti – CodingGorilla

+0

這個問題有一個更好的答案:http://stackoverflow.com/q/7013538/302677 – Rachel

回答

-1

的代碼將這個在您的​​

<Style TargetType="{x:Type ListBoxItem}"> 
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/> 
</Style> 

而在這背後

protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e) 
{ 
    ListBoxItem item = (ListBoxItem)sender; 
    item.IsSelected = true; 
} 

你可以使用下面的代碼,以及不使用代碼隱藏,但它僅保留只要它具有KeyBoard焦點,就選擇了ListBoxItem。一旦焦點離開時,該項目成爲非選擇

<Style TargetType="ListBoxItem"> 
    <Style.Triggers> 
    <Trigger Property="IsKeyboardFocusWithin" Value="True"> 
     <Setter Property="IsSelected" Value="True" /> 
    </Trigger> 
    </Style.Triggers> 
</Style> 
+0

你可能要給它信貸的地方:http://stackoverflow.com/questions/653524 /選擇一個文本框項目在一個列表框不會改變這個選擇項目的 – CodingMadeEasy

+0

@CodingMadeEasy從我已經有很長時間了upvote :)我複製這個答案[這是我的回答](http://stackoverflow.com/a/7013960/302677),這是一個非常常見的問題在網站上。 – Rachel

+0

通過重申答案,那對社區有什麼幫助?它創造了重複的答案,而不是多種答案。你應該把OP提交給你的其他答案。 – CodingMadeEasy