Click here to Skip to main content
15,893,486 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
For WPF DataGrid, you have 2 Selection Modes: Single and Extended.
For WPF ListView, you have 3 Selection Modes: Single, Multiple and Extended.

My requirement is to get the Datagrid to select items as the Multiple SelectionMode in ListView. This means:
- you select multiple items without pressing Ctrl and
- multiple items are not selected while dragging mouse inside DataGrid.

Yeah, I know I can use the ListView and style it to look like the desired Datagrid, but there's too much work done already on it (styles, event setters, DataGridCheckBoxColumns, DataGridTemplateColumns and lots more).

Has anyone solved this before? No matter if it's using code behind or extending Datagrid.
Posted
Updated 24-Apr-13 8:27am
v2
Comments
Sergey Alexandrovich Kryukov 23-Apr-13 14:26pm    
Your "there's too much work done already on it" is not a valid justification for not doing some more... I don't see how this question could make any sense.
—SA

From different sources from the web, this finally worked:

In XAML:

XML
<DataGrid.RowStyle>
    <Style TargetType="{x:Type DataGridRow}">
        <EventSetter Event="PreviewMouseDown" Handler="DataGridRowPreviewMouseDownHandler"></EventSetter>
    </Style>
</DataGrid.RowStyle>


In code-behind:
C#
private void DataGridRowPreviewMouseDownHandler(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var row = GetVisualParentByType((FrameworkElement)e.OriginalSource, typeof(DataGridRow)) as DataGridRow;
                if (row != null)
                {
                    row.IsSelected = !row.IsSelected;
                    e.Handled = true;
                }
            }
        }

        public static DependencyObject GetVisualParentByType(DependencyObject startObject, Type type)
        {
            DependencyObject parent = startObject;
            while (parent != null)
            {
                if (type.IsInstanceOfType(parent))
                    break;
                else
                    parent = VisualTreeHelper.GetParent(parent);
            }

            return parent;
        }
 
Share this answer
 
Comments
JReichert 9-Jun-21 11:21am    
Thank you. That helped me!
Shouldnt be much of an issue, you could read about the differences between a ListView and A DataGridView here:
WPF DataGrid Practical Examples[^]

And how to do multiselect here:
http://stackoverflow.com/questions/2615271/wpf-datagrid-multiselect-binding[^]

So, no worries? :-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900