Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent user from deselecting an item in a ListBox?

Tags:

c#

wpf

xaml

I've got a ListBox with a bunch of items in it. The user can click an item to edit its contents. How do I prevent the user from deselecting all items? i.e., the user shouldn't be able to have nothing selected.

like image 284
mpen Avatar asked May 01 '11 00:05

mpen


3 Answers

There is a case missing in your situation, which is when the list is cleared you will reselect an item there is no longer on the list. I solve this by adding an extra check.

        var listbox = ((ListBox)sender);
        if (listbox.SelectedItem == null)
        {
            if (e.RemovedItems.Count > 0)
            {
                object itemToReselect = e.RemovedItems[0];
                if (listbox.Items.Contains(itemToReselect))
                {
                    listbox.SelectedItem = itemToReselect;
                }
            }
        }

I then put this inside a behaviour.

like image 153
João Portela Avatar answered Oct 17 '22 07:10

João Portela


I'm not sure if there is a direct way to disable deselecting an Item, but one way which would be transparent to the user is to keep track of the last selected Item, and whenever the SelectionChanged event is raised and the selected index is -1, then reselect the last value.

like image 40
amccormack Avatar answered Oct 17 '22 07:10

amccormack


This Works for Sure to Prevent User from Deselect... Add those 2 Events to your checkedListBox1 and set the Property CheckOnClick to "True" in Design Mode. (MSVS2015)

        private void checkedListBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
        }

        private void checkedListBox1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
        }
like image 42
Kuza Grave Avatar answered Oct 17 '22 07:10

Kuza Grave