Bre*_*yan 6 wpf datagrid wpf-controls
WPF的默认行为DataGrid是选择何时单击一行(如果SelectionMode="Extended"哪个是我想要的),但是我也希望该行取消选择,如果以前在单击时已经选择了该行.
我已经尝试过以下选项,一旦选中它就会取消选择该行,似乎行选择发生在鼠标单击事件之前.
private void DoGridMouseLeftButtonUp(object sender, MouseButtonEventArgs args) {
// Get source row.
DependencyObject source = (DependencyObject)args.OriginalSource;
var row = source.FindParent<DataGridRow>();
if (row == null)
return;
// If selected, unselect.
if (row.IsSelected) {
row.IsSelected = false;
args.Handled = true;
}
}
Run Code Online (Sandbox Code Playgroud)
我用以下网格绑定到此事件的位置.
<DataGrid SelectionMode="Extended"
SelectionUnit="FullRow"
MouseLeftButtonUp="DoGridMouseLeftButtonUp">
Run Code Online (Sandbox Code Playgroud)
我已经设法解决这个问题,方法是不处理网格本身上的事件,而是在单元格上处理它们,这涉及一个事件设置器,如下所示DataGridCell:
<DataGrid SelectionMode="Extended"
SelectionUnit="FullRow">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown"
Handler="DoCheckRow"/>
</Style>
</DataGrid.Resources>
<!-- Column mapping omitted. -->
</DataGrid>
Run Code Online (Sandbox Code Playgroud)
事件处理程序代码。
public void DoCheckRow(object sender, MouseButtonEventArgs e) {
DataGridCell cell = sender as DataGridCell;
if (cell != null && !cell.IsEditing) {
DataGridRow row = FindVisualParent<DataGridRow>(cell);
if (row != null) {
row.IsSelected = !row.IsSelected;
e.Handled = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的网格是只读的,因此这里忽略任何编辑行为。
| 归档时间: |
|
| 查看次数: |
7068 次 |
| 最近记录: |