How to disable single item selection in GridView

How to disable selection of one element from a GridView?

I have a GridView with it ItemsSource associated with IEnumerable <SampleDataItem>. I would like to be able to programmatically not allow the selection of some elements in the list, while allowing others to be selected.

+6
source share
2 answers

Until I did this, you should be able to use ItemContainerStyleSelector in a GridView, the method gives you a container (GridViewItem) and the element to which you are attached. From there, you can set the IsEnabled property in the GridViewItem to false, which makes it non-selectable.

You will also probably need to choose your own style, as the default GridViewItem style will customize how the disabled item will look.

Update DataTemplateSelector Solution

public class IssueGridTemplateSelector : DataTemplateSelector { protected override DataTemplate SelectTemplateCore(object item, DependencyObject container) { var selectorItem = container as SelectorItem; if (item is Issue) return IssueTemplate; selectorItem.IsEnabled = false; selectorItem.Style = RepositoryItemStyle; return RepositoryTemplate; } public DataTemplate IssueTemplate { get; set; } public DataTemplate RepositoryTemplate { get; set; } public Style RepositoryItemStyle { get; set; } } 
+7
source

Nigel's answer is great. I just added some attached properties to the WinRT XAML Toolkit , which should make it easier if you populate the GridView with the binding of the ItemsSource properties.

For me, the usual way to change GridViewItem properties was to use the GridView.ItemContainerStyle property. Using this method, you will need to specify the IsEnabled property using styles and styles that do not support bindings in WinRT. Using an ItemContainerStyleSelector element may be one way, but this requires a custom class to be defined.

I created the GridViewItemExtensions class with the IsEnabled property, which you can set on any control in your GridView.ItemTemplate as follows:

 xmlns:xyzc="using:Xyzzer.WinRT.Controls" xyzc:GridViewItemExtensions.IsEnabled="{Binding IsEnabled}" 

The property has the behavior of finding the GridViewItem in its visual ancestor tree and storing the IsEnabled value for the GridViewItemExtensions.IsEnabled value set on its child.

Then, as Nigel said, you still need to extract the template from the GridViewItem and change it so that disabled items do not look out of place.

+6
source

Source: https://habr.com/ru/post/916506/


All Articles