使用ItemTemplate在ListBoxItems构建上添加事件

时间:2010-08-30 09:37:29

标签: wpf xaml

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

当选择ListeBoxItem时,我想要举办活动。

正如您所看到的,我尝试使用ListBoxItem.Selected="ListBoxItem_Selected",但它不起作用。

你有什么想法吗?

提前坦克!

1 个答案:

答案 0 :(得分:3)

您的处理程序不会被调用,因为ListBox已经处理了Selected事件。您应该在ListBox中处理SelectionChanged事件:

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

或者,您可以使用ItemContainerStyle将处理程序附加到每个ListBoxItem:

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