[英]How to delete a row from DataGrid control in WPF?
I know that I should use PreviewKeyDown event in order to delete a row in DataGrid so I have this code in the UI: 我知道我应该使用PreviewKeyDown事件来删除DataGrid中的一行,所以我在UI中有以下代码:
<DataGrid Name="dgPlaces"
AutoGenerateColumns="True"
ItemsSource="{Binding Places}"
PreviewKeyDown="dgPlaces_PreviewKeyDown"
/>
Then I have this code in the code-behind: 然后,我在后面的代码中有此代码:
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
}
}
}
}
I have this code in the ViewModel: 我在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");
}
}
}
And in the Model class I have Id, City and Country properties: 在Model类中,我具有Id,City和Country属性:
public class Place
{
public int Id { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
My question is related to the loop inside the code-behind file: how to extact Id from the row there so the application can know what row should be deleted? 我的问题与代码隐藏文件内部的循环有关:如何从那里的行中扩展ID,以便应用程序知道应该删除哪一行?
foreach (var row in dgPlaces.SelectedItems)
{
//here should be delete logic for each row
}
Why I can't just put . 为什么我不能放。 after row and than get Id from IntelliSense?
后排,而不是从IntelliSense获得ID? I don't get it.
我不明白
DataGrid.SelectedItems
property is non-generic, it is IList
only, row
has object
type, unless exact type is specified like this: DataGrid.SelectedItems
属性是非泛型的,仅是IList
, row
具有object
类型,除非这样指定确切类型:
foreach (Place row in dgPlaces.SelectedItems)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.