开发者

Add an event on ListBoxItems build with ItemTemplate

I have a ListBox like this :

    <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 whant to rise an event when an ListeBoxItem is selected.

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

Do you have an idea ?

Tanks by advance !


You handler doesn't get called because the Selected event is already handled by the ListBox. You should handle the SelectionChanged event in the ListBox instead:

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

Alternatively, you can use an ItemContainerStyle to attach the handler to every ListBoxItem:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜