AiNoTame

...for love
posts - 9, comments - 40, trackbacks - 0

Unselect DataGridRow in DataGrid

Oggi si è presentato il seguente problema:
Ho usato una griglia per applicare una sorta di filtro su un altro controllo in base alle DataGridRow selezionate; il cliente ha voluto che, cliccando fuori dalle colonne di una DataGrid, tutte le righe selezionate si deselezionassero (eliminando in questo modo il filtro).

L’unico modo navito per farlo è cliccare sulla DataGridRow selezionata tenendo premuto il tasto CTRL.

Ho quindi creato il codice qui sotto.
In pratica cliccando al di fuori delle colonne (parte destra della Griglia) si clicca su un elemento figlio di una DataGridRow ma non su un elemento figlio di una DataGridCell (si può vedere facilmente con WPF Inspector oppure con Snoop).
Testo quindi questa condizione e deseleziono tutto se verificata:

public static class DataGridBehaviors
    {
        public static bool GetUnselectOnClickOutside(DependencyObject obj)
        {
            return (bool)obj.GetValue(UnselectOnClickOutsideProperty);
        }
        
        public static void SetUnselectOnClickOutside(DependencyObject obj, bool value)
        { 
            obj.SetValue(UnselectOnClickOutsideProperty, value); 
        }
        public static readonly DependencyProperty UnselectOnClickOutsideProperty = 
            DependencyProperty.RegisterAttached("UnselectOnClickOutside"typeof(bool), typeof(DataGridBehaviors), 
            new UIPropertyMetadata(false, UnselectOnClickOutsidePropertyChangedCallback));
        
        private static void UnselectOnClickOutsidePropertyChangedCallback(DependencyObject depObj, DependencyPropertyChangedEventArgs eventArgs)
        {
            DataGrid grid = depObj as DataGrid;
            if (depObj != null)
            {
                if ((bool)eventArgs.OldValue == false && (bool)eventArgs.NewValue == true)     
                    grid.MouseLeftButtonUp += AssociatedObjectUnselectOnClickOutside;
                else if 
                    ((bool)eventArgs.OldValue == true && (bool)eventArgs.NewValue == false)      
                    grid.MouseLeftButtonUp -= AssociatedObjectUnselectOnClickOutside;
            }
        }
        
        private static void AssociatedObjectUnselectOnClickOutside(object sender, MouseButtonEventArgs e) 
        {
            DataGrid datagrid = e.Source as DataGrid;
            DependencyObject originalControl = e.OriginalSource as DependencyObject; 
            DataGridCell cell; DataGridRow row;
            if (TryFindParent<DataGridRow>(originalControl, out row) && !TryFindParent<DataGridCell>(originalControl, out cell)) 
            { 
                datagrid.UnselectAll();
            }
        } 
        private static bool TryFindParent<T>(DependencyObject child, out T result) where T : class 
        {
            Contract.Requires(child != null"child could not be null"); 
            Contract.Ensures(Contract.Result<bool>() == true && Contract.ValueAtReturn<T>(out result) != null
                && result is T, "Result found rule violated"); 
            Contract.Ensures(Contract.Result<bool>() == false && Contract.ValueAtReturn<T>(out result) == null, 
                "Result not found rule violated"); 
            var parent = VisualTreeHelper.GetParent(child); 
            result = parent as T;
            if (result != null)  
                return true; 
            else        
                if (parent != null)
                    return TryFindParent<T>(parent, out result);
                else 
                    return false;
        }
    }

Questo è un behavior applicabile ad ogni griglia tramite AttachedProperty:

<DataGrid ItemsSource="{Binding}" local:DataGridBehaviors.UnselectOnClickOutside="True" />

Et voilà! Les jeux sont faits

Print | posted on Wednesday, June 01, 2011 3:47 PM | Filed Under [ WP7 DependencyProperty ]

Feedback

Gravatar

# re: Unselect DataGridRow in DataGrid

What sites provide the best templates for custom essays accomplishing? I need to write academic essays. Other way I will tell someone: " Write my essay for me ".
10/20/2011 12:54 AM | Flowers19Noelle
Gravatar

# re: Unselect DataGridRow in DataGrid

Not a lot of guys can to make their websites' improvement themselves. Therefore, it is essential to find masters articles distribution company which will perform some of optimization options.
12/18/2011 3:04 AM | LizaYoung25
Gravatar

# re: Unselect DataGridRow in DataGrid

All people deserve wealthy life time and loans or credit loan would make it much better. Because people's freedom bases on money.
12/29/2011 10:55 PM | LindaAndrews22
Gravatar

# re: Unselect DataGridRow in DataGrid

How can you compose the great issue just about this good post I think over? The buy dissertation service require people like you for the thesis proposal completing. So you will have a really great opportunity to enter to the association of masters.
12/31/2011 3:12 AM | PerkinsOpal
Gravatar

# Writing

Nice Blog,I Like For Putting This Together! "This is obviously one Nice post. Thanks for the valuable information and insights you have so provided here. Keep it up!"

1/24/2012 9:17 AM | Writing Help

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 1 and 7 and type the answer here:

Powered by:
Powered By Subtext Powered By ASP.NET