C# CommandParameter multibinding返回选定行中的DataGrid控件和自定义对象
我使用的是.NET4.0,视图中有一个DataGrid。我已经实现了这一点,以提供过滤。DataGrid的ItemsSource是我的自定义对象的可观察集合。 每行都有一个按钮,单击该按钮时,通过CommandParameter将选定的自定义对象传递回C# CommandParameter multibinding返回选定行中的DataGrid控件和自定义对象,c#,wpf,mvvm,wpfdatagrid,C#,Wpf,Mvvm,Wpfdatagrid,我使用的是.NET4.0,视图中有一个DataGrid。我已经实现了这一点,以提供过滤。DataGrid的ItemsSource是我的自定义对象的可观察集合。 每行都有一个按钮,单击该按钮时,通过CommandParameter将选定的自定义对象传递回 <DataGridTemplateColumn.CellTemplate> <DataTemplate> <Button Command="{Binding Path=DataContext.Delete
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding Path=DataContext.DeleteMyCustomObjectCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding}" Width="20">
<Image Source="/MyThing;component/Images/delete.png" Height="16" Width="16"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
因为我使用的是MVVM,所以在我的ViewModel中没有对DataGrid的引用。目前,我的命令执行代码(在ViewModel中)如下所示
public void DeleteMyCustomObject(object param)
{
MyCustomObject m = param as MyCustomObject;
.....Deletion commands go here
是否有一种方法可以在我的Delete按钮的CommandParameter上使用多重绑定从当前行传回自定义对象和对实际数据网格的引用(或者有更好的解决方案)
非常感谢
Mick(1)将DataGrid.SelectedItem绑定到ViewModel中的属性
(2) 将网格作为CommandParameter发送
<DataGrid Grid.Column="2" Name="DG1" ItemsSource="{Binding}" SelectedItem="{Binding SelectedItem}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding Path=DataContext.DeleteMyCustomObjectCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGrid}}}"
CommandParameter="{Binding RelativeSource=
{RelativeSource FindAncestor,
AncestorType={x:Type DataGrid}}}" Width="20">
<Image Source="/MyThing;component/Images/delete.png" Height="16" Width="16"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn>
<DataGrid.Columns>
</DataGrid>
您能告诉我您的数据网格以及如何将CellTemplate分配给它吗?至于你的问题,我似乎不知道当你点击按钮时DataGrid.SelectedItem是如何改变的?。。。如果是这样,您可以在ViewModel中保存SelectedItem并将网格作为命令的参数发送。。。那么你就可以同时使用这两种元素了……太完美了。谢谢Eran,我以为我的解决方案过于复杂了,但却不知道该怎么做。
<DataGrid Grid.Column="2" Name="DG1" ItemsSource="{Binding}" SelectedItem="{Binding SelectedItem}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Command="{Binding Path=DataContext.DeleteMyCustomObjectCommand,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGrid}}}"
CommandParameter="{Binding RelativeSource=
{RelativeSource FindAncestor,
AncestorType={x:Type DataGrid}}}" Width="20">
<Image Source="/MyThing;component/Images/delete.png" Height="16" Width="16"/>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn>
<DataGrid.Columns>
</DataGrid>