How to disable selection a single item in a GridVi

2019-02-13 17:12发布

问题:

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.

回答1:

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;
    }
}


回答2:

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.