为什么我不能将命令绑定到双击列表框命令

Why can I not bind a command to the double click of a listbox command

我正在尝试将一个数字列表绑定到一个列表框并设置一个 doubleClickCommand,这样当我双击一个项目时它将 运行 SetItem 方法。

我的看法

 <Grid>
    <StackPanel>
        <TextBlock Text="{Binding Item}"/>
        <ListBox ItemsSource="{Binding List}" Height="515" SelectedItem="{Binding SelectedItem}" Grid.Column="0">
            <ListBoxItem>
                <ListBoxItem.InputBindings>
                    <MouseBinding Gesture="LeftDoubleClick" Command="{Binding Command}" />
                </ListBoxItem.InputBindings>
            </ListBoxItem>
        </ListBox>
    </StackPanel>
</Grid>

还有我的 ViewModel

     public class MainWindowViewModel : BindableBase
{
    public DelegateCommand Command { get; private set; }

    private string _title = "Prism Application";
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    public MainWindowViewModel()
    {
        Command = new DelegateCommand(SetItem);
        List = new List<string>();
        List.Add("one");
        List.Add("two");
        List.Add("three");
    }

    private void SetItem()
    {
        Item = SelectedItem;
    }

    private string _item;
    public string Item
    {
        get { return _item; }
        set { SetProperty(ref _item, value); }
    }

    private string _selectedItem;
    public string SelectedItem
    {
        get { return _selectedItem; }
        set { SetProperty(ref _selectedItem, value); }
    }

    private List<string> _list;
    public List<string> List
    {
        get { return _list; }
        set { SetProperty(ref _list, value); }
    }
}

当我尝试 运行 代码时,我得到了这个异常。

InvalidOperationException:使用 ItemsSource 时操作无效。使用 ItemsControl.ItemsSource 而不是

访问和修改元素

有没有办法解决这个问题;或者我需要用其他方式来做这件事吗?

异常意味着您不能同时将 ListBoxItemInputBinding 添加到 ListBox 并绑定 ItemsSource

单击 ListBoxItem 时,有多种方法可以调用命令。其中之一是在ItemTemplate中的一个元素添加一个InputBinding,例如:

<ListBox ItemsSource="{Binding List}" Height="515" SelectedItem="{Binding SelectedItem}" Grid.Column="0">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid Background="Transparent">
                <Grid.InputBindings>
                    <MouseBinding MouseAction="LeftDoubleClick"
                                  Command="{Binding DataContext.Command, 
                                      RelativeSource={RelativeSource AncestorType=ListBox}}" />
                </Grid.InputBindings>
                <TextBlock Padding="4,1" Text="{Binding}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Padding" Value="0" />
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>