功能描述:我们提供一个删除按钮,点击它可以删除当前选中的数据记录行,当然,我们也可以用Delete键盘键删除选中的记录。
一、界面修改
如同添加新记录一样,首先修改用户界面.Page.xaml代码如下:
<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data" x:Class="SLApplicationExample.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button x:Name="addButton" Content="Add" Margin="10"/>
<Button x:Name="deleteButton" Content="Delete" Margin="10"/>
</StackPanel>
<data:DataGrid x:Name="dgPeople" Grid.Row="1" />
</Grid>
</UserControl>
新用户界面如下图: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal">
<Button x:Name="addButton" Content="Add" Margin="10"/>
<Button x:Name="deleteButton" Content="Delete" Margin="10"/>
</StackPanel>
<data:DataGrid x:Name="dgPeople" Grid.Row="1" />
</Grid>
</UserControl>
二、删除按钮点击事件和键盘Delete键事件
事先要绑定事件到DataGrid控件上
this.deleteButton.Click += new RoutedEventHandler(deleteButton_Click);
this.dgPeople.KeyDown += new KeyEventHandler(peopleDataGrid_KeyDown);
1、删除按钮点击事件
this.dgPeople.KeyDown += new KeyEventHandler(peopleDataGrid_KeyDown);
#region 通过按钮删除记录
void deleteButton_Click(object sender, RoutedEventArgs e)
{
DeletePerson();
}
#endregion
2、Delete键事件
void deleteButton_Click(object sender, RoutedEventArgs e)
{
DeletePerson();
}
#endregion
#region 删除记录子程序
private void DeletePerson()
{
if (null == this.dgPeople.SelectedItem)
{
return;
}
Person person = this.dgPeople.SelectedItem as Person;
if (null == person)
{
return;
}
mypeople.Remove(person);
}
#endregion
Page.xaml.cs全部代码如下:
private void DeletePerson()
{
if (null == this.dgPeople.SelectedItem)
{
return;
}
Person person = this.dgPeople.SelectedItem as Person;
if (null == person)
{
return;
}
mypeople.Remove(person);
}
#endregion