我正在开发 WPF 应用程序。
根据要求,我想在数据网格中显示项目列表。每行还有一个“删除”按钮,使用这个按钮我们可以删除相应的项目。
我还想要网格的拖放功能。即用户可以向上/向下移动行。
我在用“PreviewMouseLeftButtonDown”
and “Drop”
数据网格的事件来实现拖放功能。
对于删除按钮,我绑定了删除命令。
Command="{Binding ElementName=viewName,Path=DataContext.DeleteCommand}"
我也尝试过
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.DeleteCommand}"
现在的问题是,当我单击“删除”按钮时,删除命令处理程序没有被触发。但是,如果我删除数据网格的“PreviewMouseLeftButtonDown”和“Drop”事件,则删除命令处理程序可以正常工作。
我还注意到,即使在添加 PreviewMouseLeftButtonDown 事件后注释了“PreviewMouseLeftButtonDown”内的所有代码,它也会阻止删除命令处理程序的执行。
<DataGridTemplateColumn Width="35" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Width="30" Content="X" Command="{Binding ElementName=viewCSW,Path=DataContext.DeleteCommand}" HorizontalAlignment="Center" Margin="0,0,0,0" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Height" Value="25"/>
</Style>
</DataGrid.RowStyle>
PreviewMousedown代码
private void dgEmployee_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition);
if (prevRowIndex < 0)
return;
dgEmployee.SelectedIndex = prevRowIndex;
var selectedEmployee = dgEmployee.Items[prevRowIndex];//as Employee;
if (selectedEmployee == null)
return;
//Now Create a Drag Rectangle with Mouse Drag-Effect
//Here you can select the Effect as per your choice
DragDropEffects dragdropeffects = DragDropEffects.Move;
if (DragDrop.DoDragDrop(dgEmployee, selectedEmployee, dragdropeffects)
!= DragDropEffects.None)
{
//Now This Item will be dropped at new location and so the new Selected Item
dgEmployee.SelectedItem = selectedEmployee;
}
// sourceElement.CaptureMouse();
// return;
}
我正在为这个问题苦苦挣扎。
如果有人有解决方案,请告诉我。
谢谢,
拉尼什