TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

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. 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.

Any help & direction on doing this is greatly appreciated!

Upvotes: 0

Views: 2196

Answers (2)

Ray Burns
Ray Burns

Reputation: 62929

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.

If you have a button in your ControlTemplate you can set its Click event exactly the same way as you would outside the ContolTemplate. 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":

<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:

<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>

Upvotes: 1

Lunivore
Lunivore

Reputation: 17657

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.

Otherwise I believe it's as simple as adding an OnClick=... in the template; the sender will be the element which got clicked.

Upvotes: 0

Related Questions