wpf mvvm datagrid 中button绑定命令方法
时间: 2023-12-09 08:04:35 浏览: 64
要在WPF MVVM中的DataGrid中绑定按钮命令方法,可以按照以下步骤进行:
1. 在ViewModel中定义一个实现ICommand接口的属性,用于绑定到Button的Command属性。
```csharp
public ICommand MyCommand { get; set; }
```
2. 在ViewModel的构造函数中实例化这个命令,并指定它的Execute和CanExecute方法。
```csharp
public MyViewModel()
{
MyCommand = new RelayCommand(ExecuteMyCommand, CanExecuteMyCommand);
}
private void ExecuteMyCommand()
{
// 在这里编写命令的执行逻辑
}
private bool CanExecuteMyCommand()
{
// 在这里编写命令的CanExecute逻辑
return true;
}
```
3. 在DataGrid中的Button中绑定这个命令。
```xml
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="Click Me" Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
```
这里使用了RelativeSource来找到DataGrid的DataContext,因为Button的DataContext是DataGrid中的每个行的数据项。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)