如何在 ViewModel 中具有删除 ICommand 定义的 DataGrid 列中执行删除按钮
How to Execute the Delete Button in a DataGrid Column having the Delete ICommand definition in ViewModel
Xaml代码
Datagrid 按钮的其他 属性 应该用于触发 CmdDeleteUser ICommand 属性。 Datagrid 行被选中,但删除按钮不起作用。
'''
<DataGridTemplateColumn Header="Delete Record" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<Button Width="60" Margin="2" Command="{Binding CmdDeleteUser}" Content="Delete" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
'''
ViewModel代码
'''
public ICommand CmdDeleteUser
{
get
{
return new DelegateCommand(DeleteUser);
}
}
private void DeleteUser()
{
if (null != SelectedCustomer)
{
customer.Remove(SelectedCustomer);
}
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand($"Delete from Customer where Id='{Convert.ToInt32(SelectedCustomer.id)}'", con);
cmd.ExecuteNonQuery();
Customer current = customer.Where(x => x.id == SelectedCustomer.id).FirstOrDefault();
customer.Remove(current);
}
catch (Exception)
{
}
finally
{
con.Close();
}
}
'''
在您的列表视图中,您可以使用 RelativeSource 访问 ViewModel 中的命令:
Command="{Binding DataContext.CmdDeleteUser, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding}
AncestorType 是您的控件的类型,它具有您需要的 Bindingcontext。
问题是您尝试在 DataGrid 中绑定 CmdDeleteUser,同时在 ViewModel 中定义了命令,但如果您使用 ItemsSource,则 DataGrid 的 BindingContext 不是 ViewModel。
Xaml代码 Datagrid 按钮的其他 属性 应该用于触发 CmdDeleteUser ICommand 属性。 Datagrid 行被选中,但删除按钮不起作用。 '''
<DataGridTemplateColumn Header="Delete Record" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate >
<DataTemplate>
<Button Width="60" Margin="2" Command="{Binding CmdDeleteUser}" Content="Delete" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
'''
ViewModel代码 '''
public ICommand CmdDeleteUser
{
get
{
return new DelegateCommand(DeleteUser);
}
}
private void DeleteUser()
{
if (null != SelectedCustomer)
{
customer.Remove(SelectedCustomer);
}
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand($"Delete from Customer where Id='{Convert.ToInt32(SelectedCustomer.id)}'", con);
cmd.ExecuteNonQuery();
Customer current = customer.Where(x => x.id == SelectedCustomer.id).FirstOrDefault();
customer.Remove(current);
}
catch (Exception)
{
}
finally
{
con.Close();
}
}
'''
在您的列表视图中,您可以使用 RelativeSource 访问 ViewModel 中的命令:
Command="{Binding DataContext.CmdDeleteUser, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding}
AncestorType 是您的控件的类型,它具有您需要的 Bindingcontext。
问题是您尝试在 DataGrid 中绑定 CmdDeleteUser,同时在 ViewModel 中定义了命令,但如果您使用 ItemsSource,则 DataGrid 的 BindingContext 不是 ViewModel。