Search code examples
c#win-universal-appwindows-10-universalwindows-10-mobile

Disable certain ListViewItem depending on custom property UWP


I have a ListView that contains several types of custom UserControls.

The project requires that some of them must be non-clickable, so I would like to disable them, but JUST THEM.

Those items will be enabled/disabled depending on the value of a custom property.

I've tried to set the ListViewItem.IsEnabled property to false, but it ain't worked, and the other solutions I've found around make no sense to me...

I let a sample of the code:

XAML

<ListView x:Name="homeLW"
                  Margin="0,5,0,0"
                  ItemClick="homeLW_ItemClick"
                  IsItemClickEnabled="True"
                  HorizontalAlignment="Center"
                  ItemsSource="{Binding Source}">

Where Source is a ObservableCollection<UserControl>.

The problem is that I can't get the items of the ListView as ListViewItems, but as the UserControl type:. When executing this:

foreach(ListViewItem lwI in homeLW.Items)
            {
                //CODE
            }

I get:

System.InvalidCastException: Unable to cast object of type UserControl.Type to type Windows.UI.Xaml.Controls.ListViewItem.

Anyone know how could I make it?

Thanks in advance :)


Solution

  • foreach(var lwI in homeLW.Items)
                {
                  ListViewItem item =(ListViewItem)homeLW.ContainerFromItem(lwI);
                  item.IsEnabled = false;
                }
    

    When on load all ListViewItems wont be loaded because of Virtualization. So you get Null when try to get container from item. Workaround would be switching off the virtualization. But it will have performance effects. Since you confirmed that it wont be having more than 20 items,I ll go ahead and add the code

    <ListView>
        <ListView.ItemsPanel> 
        <ItemsPanelTemplate> 
        <StackPanel Orientation="Vertical" /> 
        </ItemsPanelTemplate> 
        </ListView.ItemsPanel>
    </ListView>