WPF Datagrid Multiple Selection without CTRL or Space

前端 未结 4 1765
遥遥无期
遥遥无期 2021-01-05 02:20

The WPF Datagrid has two selection modes, Single or Extended. The WPF ListView has a third - Multiple. This mode allows you to click and select multiple rows without CTRL or

4条回答
  •  醉梦人生
    2021-01-05 02:43

    Based on a previous article, i wrote a ("like") MVVM code:

    Firstly add this to your main View:

      xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    

    The relevant part of View:

             
              
                              
                            
            
            
                 
              
            
             
            
           
    

    More information about EventToCommandBehavior: here

    In this way, your ViewModel must implement these commands:

        //i skipped the TouchCommand definition because MouseCommand runs for touch on screen too.
        public RelayCommand MouseCommand
        {
            get
            {
                return new RelayCommand((e)=> {
                    if (e.LeftButton == MouseButtonState.Pressed)
                    {
                        //call this function from your utils/models
                        var row = FindTemplatedParentByVisualParent((FrameworkElement)e.OriginalSource,typeof(ICommandSource));
                        //add ICommanSource to parameters. (if actual cell contains button instead of data.) Its optional.
                        if(row!=null) 
                        {
                            row.IsSelected = !row.IsSelected;
                            e.Handled = true;
                        }  
                    }                 
                });
            }
        }
    

    Finally implement a method (somewhere in Model) to find the row(s).

       public static T FindTemplatedParentByVisualParent(FrameworkElement element,Type exceptionType = null) where T : class
        {
            if (element != null && (exceptionType == null || element.TemplatedParent == null || (exceptionType != null  && element.TemplatedParent !=null && !exceptionType.IsAssignableFrom(element.TemplatedParent.GetType()))))
            {
                Type type = typeof(T);
                if (type.IsInstanceOfType(element.TemplatedParent))
                {
                    return (element.TemplatedParent as T);
                }
                else
                {
                    return FindTemplatedParentByVisualParent((FrameworkElement)VisualTreeHelper.GetParent(element));
                }
            }
            else
                return null;
        }
    

    This solution works for me perfectly so i hope it will help for you too.

提交回复
热议问题