如果已选择行,则在wpf datagrid中右键单击禁用行选择

时间:2014-05-07 03:55:23

标签: c# wpf wpfdatagrid

我正在处理一个数据网格,它允许用户选择多行。但是当用户点击行标题时,选择会丢失。

如果已经选择了行,如何在右键单击时禁用行选择。

我试图通过行为

来做到这一点
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;
        }
    }
}

但由于右键单击的其他功能也被破坏,因此无法正常工作。例如上下文菜单。上下文菜单未启用其应用程序命令。

有没有其他方法可以禁用选择,或者如果我点击任何选定的行,让选择保持不变?

1 个答案:

答案 0 :(得分:0)

您有两种选择:

  1. 创建自定义DataGridDataGridRow并创建SelectionChangingSelection个事件。需要防止选择。这一次,此控件仅包含SelectionChangedSelected个事件。下次,我想你可以编写代码

  2. 如果您不想创建自定义控件,则可以创建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);
            }
        }
    }
    
  3. 如果您愿意,可以使此代码更灵活。但您必须明白,您只能将e.Handled设置为true以阻止选择。