WinUI 3中DataTemplate内ListViewItem双击行为失效问题咨询
DataTemplate内StackPanel的DoubleTapped交互行为失效问题
我尝试为DataTemplate内的ListViewItem对应的StackPanel添加DoubleTapped事件的交互行为,代码如下:
<Button.Flyout> <Flyout> <Grid Height="500"> <ListView ItemsSource="{x:Bind ViewModel.AvailableProperties, Mode=OneWay}"> <ListView.ItemTemplate> <DataTemplate x:DataType="properties:PropertyDefinition"> <StackPanel Padding="10,5,10,5" x:Name="listViewItem"> <interactivity:Interaction.Behaviors> <core:EventTriggerBehavior EventName="DoubleTapped" SourceObject="{Binding ElementName=listViewItem}"> <core:InvokeCommandAction Command="{Binding ElementName=bomPage, Path=ViewModel.AddPropertyCommand}" CommandParameter="{x:Bind}"/> </core:EventTriggerBehavior> </interactivity:Interaction.Behaviors> <TextBlock Text="{x:Bind PropertyName}" /> <TextBlock Text="{x:Bind PropertySetName}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> </Flyout> </Button.Flyout>
当将该StackPanel移出DataTemplate时,双击行为可正常工作,但置于模板内则失效。请问我的操作是否存在错误?能否按此方式绑定该行为?
你的代码存在两个关键问题,导致DataTemplate内的交互行为失效:
ElementName绑定跨DataTemplate作用域失效
DataTemplate有自己独立的命名作用域,内部无法通过ElementName=bomPage直接绑定到页面级别的元素。移出DataTemplate后能正常工作,就是因为此时ElementName可以直接找到bomPage,而模板内不行。SourceObject绑定冗余且可能冲突
EventTriggerBehavior如果不指定SourceObject,默认会监听所在元素(也就是StackPanel)的事件,你这里绑定SourceObject="{Binding ElementName=listViewItem}"属于冗余操作,虽然不直接报错,但可能干扰事件监听逻辑。
修正方案
针对作用域问题,改用RelativeSource来查找页面级的ViewModel,同时简化EventTriggerBehavior的配置:
<Button.Flyout> <Flyout> <Grid Height="500"> <ListView ItemsSource="{x:Bind ViewModel.AvailableProperties, Mode=OneWay}"> <ListView.ItemTemplate> <DataTemplate x:DataType="properties:PropertyDefinition"> <StackPanel Padding="10,5,10,5"> <interactivity:Interaction.Behaviors> <core:EventTriggerBehavior EventName="DoubleTapped"> <core:InvokeCommandAction Command="{Binding ViewModel.AddPropertyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Page}}" CommandParameter="{x:Bind}"/> </core:EventTriggerBehavior> </interactivity:Interaction.Behaviors> <TextBlock Text="{x:Bind PropertyName}" /> <TextBlock Text="{x:Bind PropertySetName}" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> </Grid> </Flyout> </Button.Flyout>
关键改动说明
- 移除了
SourceObject属性,让EventTriggerBehavior默认监听StackPanel的DoubleTapped事件 - 将Command绑定改为通过
RelativeSource=FindAncestor查找Page类型的祖先元素,再绑定其ViewModel的AddPropertyCommand,这样就能跨DataTemplate作用域访问到页面的命令
这种方式可以正常实现DataTemplate内StackPanel的双击交互行为。
内容的提问来源于stack exchange,提问作者Bas Nederveen
相关产品推荐
相关产品推荐

