Event Firing Multiple Times

RogerSchlueter-7899 1,236 Reputation points
2023-05-10T04:59:41.88+00:00

I have a UserControl that is basically just a TreeView. This Style sets the problematic event of the TreeView Items:

<Style
    TargetType="{x:Type TreeViewItem}">
    <EventSetter Event="MouseLeftButtonUp" Handler="SelectCategory" />
    ....
</Style>

The event handler is in code-behind:

Private Sub SelectCategory(sender As Object, e As MouseButtonEventArgs)   'Handles MouseLeftButtonUp
    Dim c As Category = DirectCast(trvCategories.SelectedItem, Category)
    Debug.WriteLine(c.Name)
    ....
End Sub

The problem is that this event is firing once for every depth level of the item. For example, suppose the Categories are like this:

Category A
    Category B
        Category C

The event fires once if Category A is clicked, twice if Category B is clicked and three times if Category C is clicked. In the latter case the Debug statement produces:

Category C
Category C
Category C

How can I correct this behavior?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,636 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
778 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114K Reputation points
    2023-05-10T05:33:53.73+00:00

    Try adding e.Handled = True to your handler.


0 additional answers

Sort by: Most helpful