views:

157

answers:

3

I see a few options available for row selection, but 'No Selection' is not one of them. I've tried handling the SelectionChanged event by setting SelectedItem to null, but the row still seems selected.

If there is no easy support for preventing this, would it be easy to just style the selected row the same as an unselected one? That way it could be selected, but the user has no visual indicator.

+2  A: 

You have to call DataGrid.UnselectAll asynchronously with BeginInvoke to get it to work. I wrote the following attached property to handle this:

using System;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Windows.Controls;

namespace DataGridNoSelect
{
    public static class DataGridAttach
    {
        public static readonly DependencyProperty IsSelectionEnabledProperty = DependencyProperty.RegisterAttached(
            "IsSelectionEnabled", typeof(bool), typeof(DataGridAttach),
            new FrameworkPropertyMetadata(true, IsSelectionEnabledChanged));
        private static void IsSelectionEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var grid = (DataGrid) sender;
            if ((bool) e.NewValue)
                grid.SelectionChanged -= GridSelectionChanged;
            else
                grid.SelectionChanged += GridSelectionChanged;
        }
        static void GridSelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var grid = (DataGrid) sender;
            grid.Dispatcher.BeginInvoke(
                new Action(() =>
                {
                    grid.SelectionChanged -= GridSelectionChanged;
                    grid.UnselectAll();
                    grid.SelectionChanged += GridSelectionChanged;
                }),
                DispatcherPriority.Normal, null);
        }
        public static void SetIsSelectionEnabled(DataGrid element, bool value)
        {
            element.SetValue(IsSelectionEnabledProperty, value);
        }
        public static bool GetIsSelectionEnabled(DataGrid element)
        {
            return (bool)element.GetValue(IsSelectionEnabledProperty);
        }
    }
}

I sourced this blog post in creating my solution.

Joseph Sturtevant
This is an awesome solution to a strange problem. If I could upvote you more than once, I would! Worked perfectly.
Kilhoffer
A: 

Hi, Any row selection can be avoided using property 'IsHitTestVisible' as False. But It will not allow you to use scrollbar of your datagrid. Datagrid will be locked in this case. Another solution is: You can apply style to cell of datagrid. It worked for me. Please use code as below:
Above code worked for me. Hope it will work for you too.

Regards, Vaishali

Vaishali Choudhari
A: