【发布时间】:2016-07-03 16:25:22
【问题描述】:
我知道我应该使用 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?没看懂。
【问题讨论】: