我有一个ListBox,我试图绑定“删除”键来删除一个项目(绑定到删除命令并更新集合),但事件永远不会被触发。更有趣的是,首次加载表单时会触发事件。我有多个列表框,我想相应地处理删除。
这是xaml代码:
<ListBox x:Name="ItemListView1"
ItemsSource="{Binding Path=ItemList}"
SelectedItem="{Binding Path=SelectedItem}">
<ListBox.InputBindings>
<KeyBinding Key="Delete" Command="{Binding RemoveListView1SelectedItem}" />
</ListBox.InputBindings>
</ListBox>
这是视图模型:
private ICommand _removeListView1SelectedItem;
public ICommand RemoveListView1SelectedItem
{
get
{
return _removeListView1SelectedItem ?? (_removeListView1SelectedItem = new RelayCommand(param =>
{
if ((SelectedItem.HasValue)
&& !ItemList.Contains(SelectedItem.Value))
{
ItemList.Remove(SelectedItem.Value);
SelectedItem = null;
OnPropertyChanged("SelectedItem");
OnPropertyChanged("ItemList");
}
}));
}
}
This is the RelayCommand:
public RelayCommand(Action<object> execute) : this(execute, null)
{
}
public RelayCommand(Action<object, object> execute) : this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public RelayCommand(Action<object, object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_executeMultiParam = execute;
_canExecute = canExecute;
}