1
votes

I have a Silverlight 4.0 datagrid, which has the SelectionMode set to Single. The problem with this is that users need to CTRL+Click on an already-selected row in order to deselect it (and have nothing selected in the grid). I'd like for them to be able to simply left-click on the already-selected row to have it deselected.

I tried doing this with a SelectionChanged event (inspecting the added items in the event arguments), however it didn't work because the event isn't thrown when the user clicks on the same row twice.

Any advice?

2
That's correct. Users can't directly edit items in the grid. - Mike Cialowicz

2 Answers

0
votes

There is no way to capture the second event because it is never fired. What you could do is apply the type of customization used in this project to one that does capture the second click and fire the event a second time should you wish:

http://www.codeproject.com/KB/silverlight/doubleClickDataGridSL.aspx

0
votes

I have the same task, so here is my solution: attach handler for datagrid's MouseLeftButtonDown event using AddHandler dataGrid.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(DataGrid_MouseLeftButtonDown), true); , save SelectedIndex in private variable

    private int prevSelectedIndex;
    void DataGrid_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (prevSelectedIndex != -1 && prevSelectedIndex == dataGrid.SelectedIndex)
        {
            dataGrid.SelectedIndex = -1;
        }
        prevSelectedIndex = dataGrid.SelectedIndex;
    }

if you want reuse this logic you can create Behavior for DataGrid type

Add System.Windows.Interactivity assembly reference, add class DataGridSecondClickUnselectBehavior

public class DataGridSecondClickUnselectBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        AssociatedObject.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown), true);
    }

    private int prevSelectedIndex;
    void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        if (prevSelectedIndex != -1 && prevSelectedIndex == AssociatedObject.SelectedIndex)
        {
            AssociatedObject.SelectedIndex = -1;
        }
        prevSelectedIndex = AssociatedObject.SelectedIndex;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        AssociatedObject.RemoveHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown));
    }
}

Now after you compile solution in blend you can add this behavior simply Drag'n'drop from Assets->Behaviors to DataGrid control