【发布时间】:2015-07-22 16:16:41
【问题描述】:
我发现了一些类似的问题,但都没有完全解决我的问题,所以我整理了一个小例子。
我希望能够按 D 键,然后从 ObservableCollection 中删除该项目。这按预期工作。
然后我希望能够继续使用箭头键和 D 键从我刚刚删除的行之后的行中操作数据网格(即更新的数据网格的索引等于已删除项目的索引)。
我找到的最有用的答案是这个 - Focus on DataGridCell for SelectedItem when DataGrid Receives Keyboard Focus - 但是我不确定什么时候应该调用它,因为我想在视图更新后调用它,我目前正在使用 SelectionChanged事件,但显然这被调用得太频繁了。
任何建议都将不胜感激,我希望我在下面提供了足够的代码,以使任何人都可以重新创建项目并复制问题。
非常感谢, 迈克
我的 XAML 代码:
<Window x:Class="DataGridProblem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid ItemsSource="{Binding MyItems}"
SelectedItem="{Binding SelectedItem}">
<DataGrid.InputBindings>
<KeyBinding Key="D" Command="{Binding Delete}"/>
</DataGrid.InputBindings>
</DataGrid>
</Grid>
</Window>
我的视图模型:
namespace DataGridProblem
{
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<MyItem> _myItems;
private ICommand _delete;
public MyItem SelectedItem { get; set; }
public ICommand Delete { get { return _delete; } }
public ObservableCollection<MyItem> MyItems
{
get { return _myItems; }
set
{
_myItems = value;
OnPropertyChanged("MyItems");
}
}
public ViewModel()
{
_myItems = new ObservableCollection<MyItem>();
_myItems.Add(new MyItem() { name = "John" });
_myItems.Add(new MyItem() { name = "Mike" });
_myItems.Add(new MyItem() { name = "Phil" });
_delete = new RelayCommand(DeleteSelected);
}
private void DeleteSelected(object obj)
{
MyItems.Remove(SelectedItem);
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
我的物品:
namespace DataGridProblem
{
public class MyItem
{
public string name { get; set; }
}
}
【问题讨论】: