Search code examples
c#windowswinformswinui-3winui

In WinUI 3 In ListView How to make single item selected and other all item unselected and unclickable?


In WinUI 3 application in ListView I want one item selected and it should accept key event and other all item should be unselected and unclickable or disable. This is the code where I am trying to do this functionality,

internal static void MyListView(ListView view)
{
    view.SelectionMode = ListViewSelectionMode.None; // tried to selection mode 'none'
    foreach (var i in view.Items)
    {
        ListViewItem item = (ListViewItem)i; 
    }
}

here MyListView is method calling in separate class, there passing List view as a parameter. I tried this using setting selection mode 'none' but for perticular index item How to make selectable.

In UI I want to display Like This.

understand problem from below image. screenshot related problem

Updated:

  • In my application having scenario list of items display.

  • In that first to second last should be disabled and unclickable.

  • Last item is should be already selected and in that I am already defined a key event. when we press space key that event hit and that last item color is changing.

  • But if I click on the outside means other disable item my last item which is already selected it not accept any key event.

  • This is happening because of disabling items. In WinUi-3 when ListView Item are disabled and if we click on that through mouse then it not accept any key event which I defined already (Last Item not accept event).

  • So, I want functionality where List of items in that only last item should clickable and already click and It accept key event. if we click other disable item then also it should accept key event.

enter image description here


Solution

  • You can access each ListViewItem like this:

    // In this case "view" is your ListView control.
    foreach (object? item in view.Items)
    {
        if (view.ContainerFromItem(item) is ListViewItem listViewItem)
        {
            listViewItem.IsEnabled = listViewItem.IsSelected;
        }
    }
    

    To answer your additional question from the comments, you can programmatically select and subscribe the last item to key events, then disable the other items like this:

    // Select the last item.
    int lastItemIndex = view.Items.Count - 1;
    
    if (view.ContainerFromIndex(lastItemIndex) is ListViewItem lastListViewItem)
    {
        lastListViewItem.IsSelected = true;
        lastListViewItem.KeyDown -= ListViewItem_KeyDown;
        lastListViewItem.KeyDown += ListViewItem_KeyDown;
    }
    
    // Disable all not-selected items.
    foreach (object? item in ListViewControl.Items)
    {
        if (view.ContainerFromItem(item) is ListViewItem listViewItem)
        {
            listViewItem.IsEnabled = listViewItem.IsSelected;
        }
    }
    
    private void ListViewItem_KeyDown(object sender, KeyRoutedEventArgs e)
    {
    }