使用 ItemTemplate 在 ListBoxItems 构建上添加事件 [英] Add an event on ListBoxItems build with ItemTemplate
问题描述
我有一个像这样的 ListBox
:
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>
我想在选择 ListeBoxItem
时引发事件.
I whant to rise an event when an ListeBoxItem
is selected.
如您所见,我已尝试使用 ListBoxItem.Selected="ListBoxItem_Selected"
但它不起作用.
As you can see, I've tried with ListBoxItem.Selected="ListBoxItem_Selected"
but it does not work.
你有什么想法吗?
提前准备坦克!
推荐答案
您的处理程序没有被调用,因为 Selected 事件已经由 ListBox 处理.您应该处理 SelectionChangedListBox 中的事件:
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">
或者,您可以使用 ItemContainerStyle 将处理程序附加到每个 ListBoxItem:
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>
这篇关于使用 ItemTemplate 在 ListBoxItems 构建上添加事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!