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

为什么无法给ListBox绑定双击命令?运行时报ItemsSource相关异常如何修复?

错误原因

该报错的核心是WPF的ListBox不支持同时使用ItemsSource绑定数据源和手动添加ListBoxItem子元素。你当前的XAML代码中,既给ListBox绑定了ItemsSource="{Binding List}"让控件自动生成列表条目,又手动写了一个<ListBoxItem>节点,两种条目管理方式冲突触发了异常。

修复方案

无需修改现有ViewModel逻辑,仅调整XAML代码,将双击命令绑定写到ListBox.ItemContainerStyle中,给所有自动生成的列表条目统一添加双击触发规则即可:

<Grid>
    <StackPanel>
        <TextBlock Text="{Binding Item}"/>
        <ListBox ItemsSource="{Binding List}" 
                 Height="515" 
                 SelectedItem="{Binding SelectedItem}" 
                 Grid.Column="0">
            <!-- 给自动生成的每一个ListBoxItem统一配置双击绑定 -->
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="InputBindings">
                        <Setter.Value>
                            <InputBindingCollection>
                                <MouseBinding Gesture="LeftDoubleClick" 
                                              Command="{Binding DataContext.Command, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBox}}" />
                            </InputBindingCollection>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
    </StackPanel>
</Grid>

修改后运行程序,双击任意列表条目就会触发SetItem方法,实现你需要的赋值效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 11:54:07