[英]Disable the row selection on right click in wpf datagrid if row is already selected
我正在一个数据网格上,它使用户可以选择多行。 但是,当用户单击行标题时,选择内容将丢失。
如果已经选择了行,如何右键单击禁用行选择。
我试图通过行为来做到这一点
public class DataGridRowBehavior
{
public static readonly DependencyProperty DisableSelectionOnRightClickProperty = DependencyProperty.RegisterAttached(
"DisableSelectionOnRightClick",
typeof(bool),
typeof(DataGridRowBehavior),
new UIPropertyMetadata(false, OnDisableSelectionOnRightClick));
public static bool GetDisableSelectionOnRightClick(DependencyObject dgRow)
{
return (bool)dgRow.GetValue(DisableSelectionOnRightClickProperty);
}
public static void SetDisableSelectionOnRightClick(DependencyObject dgRow, bool value)
{
dgRow.SetValue(DisableSelectionOnRightClickProperty, value);
}
public static void SetListViewFocus(DependencyObject d, bool use)
{
d.SetValue(DisableSelectionOnRightClickProperty, use);
}
public static void OnDisableSelectionOnRightClick(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGridRowHeader header = d as DataGridRowHeader;
header.MouseRightButtonUp += header_MouseRightButtonUp;
}
static void header_MouseRightButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
var header = sender as DataGridRowHeader;
if (header.IsRowSelected)
{
if (header.ContextMenu != null)
{
header.ContextMenu.IsOpen = true;
}
e.Handled = true;
}
}
}
但这不能正常工作,因为右键单击的其他功能也已损坏。 例如,上下文菜单。 上下文菜单未启用其“应用程序命令”。
如果单击任何选定的行,还有其他方法可以禁用选择或让选择保持原样吗?
您有两种选择:
创建自定义DataGrid
或DataGridRow
并创建SelectionChanging
或Selection
事件。 需要防止选择。 这次,此控件仅具有SelectionChanged
和Selected
事件。 下次,我认为您可以编写代码
如果不想创建自定义控件,则可以创建一个Behavior
。 例如:
public class SuppressButtonClickBehavior : Behavior<Button> { protected override void OnAttached() { base.OnAttached(); AssociatedObject.AddHandler(UIElement.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler(OnPreviewMouseLeftButtonDown), true); } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.RemoveHandler(UIElement.PreviewMouseLeftButtonDownEvent, new RoutedEventHandler(OnPreviewMouseLeftButtonDown)); } private void OnPreviewMouseLeftButtonDown(Object sender, RoutedEventArgs e) { e.Handled = true; if (AssociatedObject.Command != null) { AssociatedObject.Command.Execute(AssociatedObject.CommandParameter); } } }
如果需要,可以使此代码更灵活。 但是您必须了解,只能将e.Handled
设置为true
以防止选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.