繁体   English   中英

在ControlTemplate中单击ListBoxItem时需要触发事件

[英]Need to trigger an event when ListBoxItem is clicked in ControlTemplate

我用ControlTemplate覆盖了ListBoxItems的样式,但是这样做,我失去了ListBoxItem click事件的处理程序。 我找到了一篇有助于说我需要在ControlTemplate中添加事件处理程序的帖子,但是我不知道该怎么做。

对此的任何帮助和指导将不胜感激!

ListBoxItem没有“ click”事件,因此不清楚在添加ControlTemplate时您正在做什么或失去了哪些功能。

如果ControlTemplate中有一个按钮,则可以与在ContolTemplate外部完全相同的方式设置其Click事件。 这是一个简单的示例,其中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>

如果您要表示的是您希望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>

确实是您想要的鼠标单击,还是只是响应选择的更改? 如果是这样,您可能要改用ListBox.SelectionChanged。

否则,我认为它就像在模板中添加OnClick = ...一样简单; 发送者将是被单击的元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM