开发者

Need to trigger an event when ListBoxItem is clicked in ControlTemplate

开发者 https://www.devze.com 2023-01-04 06:37 出处:网络
I\'m overriding the styles of my ListBoxItems with a ControlTemplate, however by doing that, I lost the handler for my ListBoxItem click event.开发者_如何学CI found a post that was helpful in saying I

I'm overriding the styles of my ListBoxItems with a ControlTemplate, however by doing that, I lost the handler for my ListBoxItem click event. 开发者_如何学CI 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!


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>


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号