Disable certain ListViewItem depending on custom p

2019-05-12 14:34发布

问题:

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 :)

回答1:

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>


回答2:

To add onto LoveToCode's answer, if you want to disable the selected items on load and not turn off Virtualization, you'll need to fire the code when the UIElement is loaded. Otherwise, you'll get a System.NullReferenceException. The reason for this is because the Framework Element hasn't been loaded to reference the ListView Container.

homeLW.Loaded += DisableSelectedItemsOnLoad()

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