没有触发键绑定(bind)的 WPF MVVM 命令

标签 wpf data-binding mvvm

按下删除键不会导致下面的命令触发。可以假设 DelegateCommand 遵循接口(interface)契约,因为 View 中引用的其他 DelegateCommand 实例在 ViewModel 中正确触发。

为什么?

查看:

<ListBox Height="132"
     Name="lbFiles"
     ItemsSource="{Binding LbItems, UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"  
     VerticalAlignment="Center"
     SelectedValue="{Binding Path=ListBoxSelection}">
<ListBox.InputBindings>
    <KeyBinding Key="Delete"
                Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}
                ,Path=DataContext.CommandInputFilesDeleteSelected}" />
</ListBox.InputBindings>

查看型号:

private DelegateCommand commandInputFilesDeleteSelected;

public ICommand CommandInputFilesDeleteSelected {
    get {
            if (commandInputFilesDeleteSelected == null) {
                commandInputFilesDeleteSelected = new DelegateCommand(InputFilesDeleteSelected);
            }
    return saveCommand;
    }
}

private void InputFilesDeleteSelected() { //this never fires :( 
        LbItems.Remove(ListBoxSelection); 
}

最佳答案

private DelegateCommand commandInputFilesDeleteSelected;

public ICommand CommandInputFilesDeleteSelected {
    get {
            if (commandInputFilesDeleteSelected == null) {
                commandInputFilesDeleteSelected = new DelegateCommand(InputFilesDeleteSelected);
            }
    return saveCommand;  //changed from saveCommand to commandInputFilesDeleteSelected whoops
    }
}

关于没有触发键绑定(bind)的 WPF MVVM 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14613478/

相关文章:

c# - WPF:修剪所有文本框

c# - 带有全选复选框的多选 ListView 。绑定(bind)属性上的数据触发

android - TextView textColor 中的数据绑定(bind)选择器

c# - 我应该将 EF DBContext 对象保留在其自己的模块中,然后通过 DI 获取它吗?

c# - View 更改后自动 INotifyPropertyChanged

wpf - 并排放置堆叠面板

c# - WPF Web 应用程序未显示

wpf - 绑定(bind)文本 block 样式/转换器

android - 按钮中的 onClick 不起作用使用数据绑定(bind)

c# - 通知 ui wpf 中另一个线程发生了什么的最佳方法?