[英]Need to trigger an event when ListBoxItem is clicked in ControlTemplate
I'm overriding the styles of my ListBoxItems with a ControlTemplate, however by doing that, I lost the handler for my ListBoxItem click event. 我用ControlTemplate覆盖了ListBoxItems的样式,但是这样做,我失去了ListBoxItem click事件的处理程序。 I found a post that was helpful in saying I need to add an event handler in the ControlTemplate, but I don't know how to do this. 我找到了一篇有助于说我需要在ControlTemplate中添加事件处理程序的帖子,但是我不知道该怎么做。
Any help & direction on doing this is greatly appreciated! 对此的任何帮助和指导将不胜感激!
ListBoxItem doesn't have a "click" event, so it is not clear what you were doing or what functionality you lost when you added the ControlTemplate. ListBoxItem没有“ click”事件,因此不清楚在添加ControlTemplate时您正在做什么或失去了哪些功能。
If you have a button in your ControlTemplate you can set its Click event exactly the same way as you would outside the ContolTemplate. 如果ControlTemplate中有一个按钮,则可以与在ContolTemplate外部完全相同的方式设置其Click事件。 Here's a simple example where ListBoxItem does nothing other than show a Button beside the content, and that button calls an event handler named "OnClickMeButtonClicked": 这是一个简单的示例,其中ListBoxItem除了在内容旁边显示一个Button之外不执行其他操作,并且该按钮调用名为“ OnClickMeButtonClicked”的事件处理程序:
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<DockPanel>
<Button Content="ClickMe" Click="OnClickMeButtonClicked" />
<ContentPresenter />
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
If what you meant is you want your ListBoxItem to display differently depending on whether the item is selected or not, just set a trigger on IsSelected: 如果您要表示的是您希望ListBoxItem根据是否选中该项目而不同地显示,则只需在IsSelected上设置一个触发器即可:
<ControlTemplate TargetType="ListBoxItem">
<Border Name="Bd">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="Bd" Property="Background" Value="Blue" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
Is it really the mouse click you're after, or are you just responding to a change in selection? 确实是您想要的鼠标单击,还是只是响应选择的更改? If so, you may want to use ListBox.SelectionChanged instead. 如果是这样,您可能要改用ListBox.SelectionChanged。
Otherwise I believe it's as simple as adding an OnClick=... in the template; 否则,我认为它就像在模板中添加OnClick = ...一样简单; the sender will be the element which got clicked. 发送者将是被单击的元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.