Disable certain ListViewItem depending on custom property UWP

笑着哭i 提交于 2020-01-02 07:34:49

问题


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


来源:https://stackoverflow.com/questions/37132267/disable-certain-listviewitem-depending-on-custom-property-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!