C# DataGrid按钮,命令绑定树上的相对源不工作
我有一个数据网格,只有很少的文本列和一个删除按钮:C# DataGrid按钮,命令绑定树上的相对源不工作,c#,wpf,xaml,datagrid,C#,Wpf,Xaml,Datagrid,我有一个数据网格,只有很少的文本列和一个删除按钮: <DataGrid ItemsSource="{Binding Customers, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" CanUserAddRows="False" SelectedItem="{Binding SelectedCustomer}"> <DataGrid.Colu
<DataGrid ItemsSource="{Binding Customers, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" CanUserAddRows="False" SelectedItem="{Binding SelectedCustomer}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding FirstName}">
<DataGridTextColumn.Header>
<Label Content="{DynamicResource FirstName}" />
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding LastName}">
<DataGridTextColumn.Header>
<Label Content="{DynamicResource LastName}" />
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTextColumn Binding="{Binding Address}">
<DataGridTextColumn.Header>
<Label Content="{DynamicResource Address}" />
</DataGridTextColumn.Header>
</DataGridTextColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{DynamicResource Delete}" Command="{Binding DeleteCustomerCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding SelectedCustomer, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
部分。然而,没有任何东西仍然有效。使用调试时,可以看到数据上下文设置正确。DataGrid
的datacontext是ViewModel,它使用Customers
collection属性,网格行的数据上下文是预期的单个Customer
对象。
我已经检查了命令是否以真实名称引用,并且它们是否是公共的。命令在ViewModel的构造函数中初始化:
DeleteCustomerCommand = new RelayCommand<Customer>(DeleteCustomer);
DeleteCustomerCommand=新的RelayCommand(DeleteCustomer);
并且这些命令是带有私有setter的公共属性:
public RelayCommand<Customer> DeleteCustomerCommand { get; private set; }
public RelayCommand DeleteCustomerCommand{get;private set;}
我只得到以下错误:
在“对象”“数据网格”上未找到DeleteCustomerCommand属性
(名称=“”)。BindingExpression:Path=DeleteCustomerCommand;
DataItem='DataGrid'(名称='');目标元素是“按钮”(名称=“”);
目标属性为“Command”(类型为“ICommand”)
尝试将“DataContext”添加到命令绑定:
Command="{Binding DataContext.DeleteCustomerCommand, RelativeSource=...
因为在DataGrid
上没有DeleteCustomerCommand
属性,但是在与DataGrid
连接的视图模型中没有
其他信息 有时,它可以帮助我使用Visual Studio assistant为
DataContext
创建绑定,而不是完全手工编写。
只需在控件的属性网格中查找要为其创建绑定的属性
在这种情况下,它是
命令
属性。在命令属性文本的文本框上单击鼠标左键,然后从关联菜单中选择“创建数据绑定…”。单击该按钮时,是否在输出窗口中检查了任何绑定错误?谢谢提供更多信息。它一定会派上用场的!
Command="{Binding DataContext.DeleteCustomerCommand, RelativeSource=...