我知道我应该使用PreviewKeyDown事件来删除DataGrid中的一行,所以我在UI中有这个代码:
<DataGrid Name="dgPlaces"
AutoGenerateColumns="True"
ItemsSource="{Binding Places}"
PreviewKeyDown="dgPlaces_PreviewKeyDown"
/>
然后我在代码隐藏中使用了这段代码:
private void dgPlaces_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (dgPlaces.SelectedItems.Count > 0)
{
foreach (var row in dgPlaces.SelectedItems)
{
//here should be delete logic for each row
}
}
}
}
我在ViewModel中有这段代码:
public class ViewModel //: INotifyPropertyChanged
{
public ViewModel()
{
}
private ObservableCollection<Place> places = new ObservableCollection<Place>()
{
new Place { Id = 1, City = "New York", Country = "US" },
new Place { Id = 2, City = "Chicago", Country = "US" },
new Place { Id = 3, City = "Miami", Country = "US" }
};
public ObservableCollection<Place> Places
{
get
{
return places;
}
set
{
places = value;
RaisePropertyChanged("Places");
}
}
}
在Model类中,我有Id,City和Country属性:
public class Place
{
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
我的问题与代码隐藏文件中的循环有关:如何从那里的行中取代Id,以便应用程序可以知道应该删除哪一行?
foreach (var row in dgPlaces.SelectedItems)
{
//here should be delete logic for each row
}
为什么我不能放。在行之后,而不是从IntelliSense获取Id?我不明白。
答案 0 :(得分:1)
DataGrid.SelectedItems
属性是非通用的,仅IList
,row
具有object
类型,除非指定了确切的类型:
foreach (Place row in dgPlaces.SelectedItems)
{
}