You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

嵌套ListView绑定双击事件问题:RelayCommand未触发

问题分析与解决方法

你遇到的问题核心有两个:一是双击事件绑定的对象不对(你绑定给了内层ListView而非ListViewItem),二是原写法依赖SelectedItem的时机可能存在时序问题。下面是具体的修复方案:

错误原因拆解

  1. 事件绑定目标错误:你把MouseBinding加在了内层ListView控件本身上,而不是列表项ListViewItem上。双击列表项时,事件会被ListViewItem本身捕获,不会传递到外层的ListView控件,导致你的命令永远不会触发。
  2. SelectedItem时序问题:即使事件能触发,双击操作和SelectedItem的更新可能存在先后差,导致CommandParameter拿到旧值甚至null,如果你的RelayCommand有CanExecute逻辑,可能直接跳过执行。

正确的XAML写法

我们需要把双击事件绑定到内层ListView的每个ListViewItem上,同时直接绑定当前Item的上下文作为参数,不需要依赖SelectedItem:

<UserControl>
<UserControl.Resources>
<DataTemplate x:Key="DefaultTemplate">
<ListView Name="jobsView" ItemsSource="{Binding jobs}" SelectedItem="{Binding Path=SelectedProduction}" >
    <!-- 给ListViewItem添加双击绑定 -->
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="InputBindings">
                <Setter.Value>
                    <InputBindingCollection>
                        <MouseBinding 
                            Gesture="LeftDoubleClick" 
                            <!-- 绑定到UserControl的DataContext(ViewModel)里的命令 -->
                            Command="{Binding DataContext.ItemSelectedCommand, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"
                            <!-- 直接传递当前ListViewItem绑定的数据对象作为参数 -->
                            CommandParameter="{Binding}" />
                    </InputBindingCollection>
                </Setter.Value>
            </Setter>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>
</DataTemplate>
</UserControl.Resources>
<ListView Name="weekView" ItemsSource="{Binding dayList}" ItemTemplate="{StaticResource DefaultTemplate}" >
</ListView>
</UserControl>

补充说明

  • 你之前的RelativeSource={RelativeSource AncestorType={x:Type UserControl}}写法其实是正确的,它会向上查找最近的UserControl实例,拿到其DataContext(也就是你的ViewModel),所以命令绑定路径本身没有问题。
  • 用CommandParameter="{Binding}"直接传递当前列表项的绑定对象,比依赖SelectedItem更可靠,彻底避免了时序问题。
  • 如果你的RelayCommand需要接收SelectedProduction类型的参数,这个写法完全适配,因为{Binding}就是当前jobs集合里的单个对象。

内容的提问来源于stack exchange,提问作者ManuKILLED

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:58:11