我有幾個文本列的數據網格和刪除按鈕樹:DataGrid的按鈕,命令結合相對源漲不工作
<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?
我addded的
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}
一部分。但是,沒有任何工作仍然。當我使用Snoop進行調試時,我可以看到DataContexts已正確設置。 DataGrid
的datacontext是ViewModel,它使用Customers
集合屬性,並且網格行的數據上下文是單個的Customer
對象,這是預期的。 我已經檢查過,這些命令是用真實名稱來引用的,而且它們是公開的。命令初始化在視圖模型的構造:
DeleteCustomerCommand = new RelayCommand<Customer>(DeleteCustomer);
和命令與私營制定者的公共屬性:
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')
您是否在點擊按鈕時檢查了輸出窗口中的任何綁定錯誤? – Martin