2011-09-22 56 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