我有一个包含几个文本列和一个删除按钮的数据网格:
<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>
读完这个问答:
How to use RelativeSource Binding to create DataGrid binding to Model and ViewModel?
我添加了
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}
部分。但是,仍然没有任何效果。当我用 Snoop 调试时,我可以看到 DataContexts 已正确设置。 DataGrid
的数据上下文是 ViewModel,它使用 Customers
集合属性,网格行的数据上下文是单个 Customer
对象,这是预期的。
我检查过命令是否以真实姓名引用,并且它们是公开的。命令在 ViewModel 的构造函数中初始化:
DeleteCustomerCommand = new RelayCommand<Customer>(DeleteCustomer);
并且命令是具有私有(private) setter 的公共(public)属性:
public RelayCommand<Customer> DeleteCustomerCommand { get; private set; }
我只收到以下错误:
DeleteCustomerCommand' property not found on 'object' ''DataGrid' (Name='')'. BindingExpression:Path=DeleteCustomerCommand; DataItem='DataGrid' (Name=''); target element is 'Button' (Name=''); target property is 'Command' (type 'ICommand')
最佳答案
尝试将“DataContext”添加到您的命令绑定(bind):
Command="{Binding DataContext.DeleteCustomerCommand, RelativeSource=...
因为 DataGrid
上没有 DeleteCustomerCommand
属性,但是在与 DataGrid
连接的 View 模型中。
附加信息
有时它可以帮助我使用 Visual Studio 助手为 DataContext
创建绑定(bind),而不是完全手动编码。
只需在控件的属性网格中查找要为其创建绑定(bind)的属性。
在本例中,它是 Command
属性。左键单击命令属性文本的文本框,然后从上下文菜单中选择“创建数据绑定(bind)...”。
关于c# - DataGrid 按钮,树上的命令绑定(bind)相对源不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33172423/