AFAIK冒泡意味着,如果在子级上触发事件,则在父级上也会触发相同的事件。
我有一段代码:
<ListView Name="lvFiles" SelectedItem="{Binding SelectedTabFilePath, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding Path=SelectedItem.Files,ElementName=trvFiles, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Path=Name}"
Command="{Binding DataContext.OpenFileFromTreeView,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
CommandParameter="{Binding DataContext,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}}"
Background="Transparent"
BorderBrush="Transparent"
>
</Button>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
问题是,如果我单击按钮,SelectedItem
的属性SelectedTabFilePath
将不会填充数据(因为我没有单击ListView
的项目(。
所以,我的问题是:有没有办法触发按钮的Click
事件和ListView
事件?
如果没有,当我也单击该按钮时,从SelectedItem
属性设置SelectedTabFilePath
的方法是什么?
Click事件确实在冒泡,这意味着它将向上路由到可视化树的元素,直到到达根元素。但是,Button
本身处理事件,因为其Command
属性已绑定。这意味着它的父元素,包括ListViewItem
(项目容器(将忽略该事件,否则不会选择该项目。
有一种解决方法,即Button
在单击时接收键盘焦点。添加一个带有触发器的项容器样式,该触发器在键盘焦点位于ListViewItem
内时设置IsSelected
属性,由IsKeyboardFocusWithin
属性表示。
<ListView ...>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True"/>
</Trigger>
</Style.Triggers>
</Style>
</ListView.ItemContainerStyle>
<!-- ...your other markup. -->
</ListView>
如何使用MVVM 处理WPF列表框选择更改事件
我认为,当列表框选择发生更改时,可以使用交互来触发相同的命令(OpenFileFromTreeView(。
代替:
AncestorType={x:Type ListView}
如果你尝试:
AncestorType={x:Type ListViewItem}