以前作了一個使用ListBox控件動態顯示人員信息而且雙擊修改人員基本信息的功能,示意圖以下:測試
今天測試的時候發現只要有選中的對象,雙擊空白的地方也能夠觸發雙擊事件,查看代碼才發現,是把事件寫在ListBox上面了,因此只要雙擊ListBox就能夠觸發事件,修改代碼,把事件放到DataTemPlate中:spa
<DataTemplate x:Key="persontemplate"> <StackPanel x:Name="item" Orientation="Vertical"> <i:Interaction.Triggers> <i:EventTrigger EventName="PreviewMouseDoubleClick" > <i:InvokeCommandAction Command="{Binding Path=DataContext.EditCommand}" CommandParameter="{Binding Content, RelativeSource ={RelativeSource AncestorType={x:Type ListBoxItem}}}"/> </i:EventTrigger> </i:Interaction.Triggers> <Image Width="145" Height="145" Stretch="Fill" Source="{Binding Path=show_pic,Converter={StaticResource FacePictureConverter},ConverterParameter=145|145,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> </Image> <Grid Width="145" Height="22"> <TextBlock Text="{Binding p_name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="14" Foreground="{StaticResource RichImageTextForeground}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock> </Grid> </StackPanel> </DataTemplate>
運行,雙擊圖片不能出觸發,是由於StacKPanel 不支持PreviewMouseDoubleClick事件,因而在stackpanel外面套上ContentControl,可是運行的時候仍是不能觸發。code
查找資料,給ListBox一個Name,將Command綁定時添加ElementName=personListBox,運行成功,代碼以下:對象
<ListBox x:Name="personListBox" ItemsSource="{Binding PersonList}" SelectedItem="{Binding CurrentPerson,Mode=TwoWay}" ItemTemplate="{DynamicResource persontemplate}" ItemContainerStyle="{StaticResource PersonListBoxStyle}"> <ListBox.Template> <ControlTemplate TargetType="{x:Type ListBox}"> <ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled" > <WrapPanel Orientation="Horizontal" IsItemsHost="True" ScrollViewer.CanContentScroll="True"/> </ScrollViewer> </ControlTemplate> </ListBox.Template> <ListBox.Resources> <DataTemplate x:Key="persontemplate"> <ContentControl> <i:Interaction.Triggers> <i:EventTrigger EventName="PreviewMouseDoubleClick" > <i:InvokeCommandAction Command="{Binding ElementName=personListBox, Path=DataContext.EditCommand}" CommandParameter="{Binding Content, RelativeSource ={RelativeSource AncestorType={x:Type ListBoxItem}}}"/> </i:EventTrigger> </i:Interaction.Triggers> <StackPanel x:Name="item" Orientation="Vertical"> <Image Width="145" Height="145" Stretch="Fill" Source="{Binding Path=show_pic,Converter={StaticResource FacePictureConverter},ConverterParameter=145|145,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> </Image> <Grid Width="145" Height="22"> <TextBlock Text="{Binding p_name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" FontSize="14" Foreground="{StaticResource RichImageTextForeground}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock> </Grid> </StackPanel> </ContentControl> </DataTemplate> </ListBox.Resources> </ListBox>
雖然功能完成,可是不明白爲何,但願有人能夠解惑。blog