0

我用 ControlTemplate 覆盖了我的 ListBoxItems 的样式,但是这样做,我丢失了我的 ListBoxItem 单击事件的处理程序。我发现一篇文章有​​助于说我需要在 ControlTemplate 中添加一个事件处理程序,但我不知道该怎么做。

非常感谢您对此的任何帮助和指导!

4

2 回答 2

1

ListBoxItem 没有“单击”事件,因此不清楚您在做什么或添加 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>
于 2010-06-17T12:26:25.743 回答
0

真的是您所追求的鼠标点击,还是您只是响应选择的变化?如果是这样,您可能希望改用 ListBox.SelectionChanged。

否则我相信它就像在模板中添加 OnClick=... 一样简单;发件人将是被点击的元素。

于 2010-06-17T10:15:15.917 回答