WPF MVVM 实现Button按钮删除选中的DataGrid的某一行

代码如下:

删除按钮前端代码:

<Button Content="删除" Background="#F39DA6" FontSize="12" Margin="5" Width="65" Height="33">
	<Button.Template>
		<ControlTemplate TargetType="{x:Type Button}">
			<Border BorderThickness="1" CornerRadius="3" Background="{TemplateBinding Background}">
				<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center"/>
			Border>
		ControlTemplate>
	Button.Template>  
	<b:Interaction.Triggers>
		<b:EventTrigger EventName="Click">
			<b:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:ManagerView}}, Path=DataContext.DeleteManagerCommand}"
                                                   CommandParameter="{Binding}"/>
		b:EventTrigger>
	b:Interaction.Triggers>
Button>

DataGrid前端代码:

<DataGrid x:Name="dataGrid" Grid.Row="1" ItemsSource="{Binding Managers}" AutoGenerateColumns="False"
                       CanUserAddRows="False" ColumnHeaderStyle="{StaticResource ColumnHeaderStyle}" ColumnWidth="*">
	<DataGrid.Columns>  
		<DataGridTextColumn Header="用户名" Binding="{Binding manager_name}"/>
		<DataGridTextColumn Header="账号" Binding="{Binding manager_id}"/>
		<DataGridTextColumn Header="年龄" Binding="{Binding age}"/>
		<DataGridTextColumn Header="性别" Binding="{Binding sex}"/>
		<DataGridTextColumn Header="电话" Binding="{Binding telephone, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
		<DataGridTextColumn Header="密码" Binding="{Binding password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
	DataGrid.Columns>
DataGrid>

删除按钮绑定的Command后端ViewModel代码:

public RelayCommand<object> DeleteManagerCommand
{
	get
	{
		return new RelayCommand<object>((arg) =>
		{
			var Model = AppData.Instance.DataGrid.SelectedItem as manager;  //AppData.Instance.DataGrid.SelectedValue表示鼠标当前选中的DataGrid的某一行
			//AppData.Instance.DataGrid是定义在APPData类中的属性,该属性的值是在定义DataGrid控件(窗体)的构造函数中获取的,如下所示
			//AddData.Instance,DataGrid = dataGrid;  dataGrid是前端定义的DataGrid的名称
			var count = new ManagerProvider().Delete(Model);
			if (count > 0)
			{
				MessageBox.Show("删除成功", "提示");
			}
			Managers = new ManagerProvider().Select();  //刷新DataGrid
		});
	}
}

注意:DataGrid的SelectedItem属性不能绑定值,不然删除数据时,数据库会正常删除,但是DataGrid会被清空

你可能感兴趣的:(WPF,wpf)