Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable selection a single item in a GridView

How do you disable the selection single item from a GridView?

I have a GridView with it's ItemsSource bound to an IEnumerable<SampleDataItem>. I'd like to be able to programmatically not allow the selection of some items in the list while allowing selection of the others.

like image 525
Michael Avatar asked May 23 '12 23:05

Michael


2 Answers

While I haven't done this, you should be able to use an ItemContainerStyleSelector on the GridView, the method gives you the container (GridViewItem) and the item you're binding to. From there you can set the IsEnabled property on the GridViewItem to false which makes it unselectable.

You'll also probably need to select a custom style as well since the default GridViewItem style will customise how a 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;
    }
}
like image 155
Nigel Sampson Avatar answered Nov 15 '22 11:11

Nigel Sampson


Nigel's answer is great. I just added some attached properties to the WinRT XAML Toolkit that should make it simpler to do if you are populating your GridView using the ItemsSource property binding.

For me the usual way to modify the GridViewItem properties then was using GridView.ItemContainerStyle property. Using that method you would need to specify the IsEnabled property using a style and style setters don't support bindings in WinRT. Using the ItemContainerStyleSelector might be one way, but it requires defining a custom class.

I have created a GridViewItemExtensions class with an IsEnabled property that you can set on any control in your GridView.ItemTemplate like this:

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

The property has a behavior of finding the GridViewItem in its ancestors visual tree and keeping its IsEnabled value synchronized to the GridViewItemExtensions.IsEnabled value set on its descendant.

Then as Nigel said - you still need to extract the template from a GridViewItem and modify it so the disabled items don't look out of place.

like image 37
Filip Skakun Avatar answered Nov 15 '22 10:11

Filip Skakun