Adding an event to the ListBoxItems assembly using ItemTemplate

I have ListBox:

    <ListBox DataContext="{Binding UpdateSourceTrigger=PropertyChanged}"
             ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}"
             ListBoxItem.Selected="ListBoxItem_Selected">
        <ListBox.ItemTemplate>
            <DataTemplate>
                   <StackPanel>
                        <DockPanel>
                            <Label Content="{Binding Path=Attribute[rdv].Value, UpdateSourceTrigger=PropertyChanged}" />
                        </DockPanel>
                        <DockPanel>
                            <Label Content="{Binding Path=Attribute[type].Value, UpdateSourceTrigger=PropertyChanged}" />
                            <Label Content="{Binding Path=Element[ville].Attribute[saisie].Value, UpdateSourceTrigger=PropertyChanged}" />
                            <Label Content=":" />
                            <Label Content="{Binding Path=Element[adresse].Attribute[saisie].Value, UpdateSourceTrigger=PropertyChanged}" />
                        </DockPanel>
                        <Separator />
                    </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

I want to create an event when selected ListeBoxItem.

As you can see, I tried with ListBoxItem.Selected="ListBoxItem_Selected", but it does not work.

Do you have an idea?

Tanks in advance!

+3
source share
1 answer

The handler is not called because the selected event is already being processed by the ListBox. You must handle the SelectionChanged event in the ListBox:

<ListBox DataContext="{Binding UpdateSourceTrigger=PropertyChanged}"
        ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}"
        SelectionChanged="ListBox_SelectionChanged">

Alternatively, you can use ItemContainerStyle to attach a handler to each ListBoxItem:

<ListBox DataContext="{Binding UpdateSourceTrigger=PropertyChanged}"
        ItemsSource="{Binding UpdateSourceTrigger=PropertyChanged}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="Selected" Handler="ListBoxItem_Selected"/>
        </Style>
    </ListBox.ItemContainerStyle>
+3
source

Source: https://habr.com/ru/post/1762253/


All Articles