Select an item two or more times

不羁岁月 提交于 2019-12-24 07:46:56

问题


I have a Listbox with its DataContext. When I select an item, I can't select the same again. This is not a problem when there are many objects, but sometimes, a post-service return me a list with only one element, and if the user select the element and he wants select it again, he will not can do it. Anyone knows how to resolve this problem

Anyway, thanks!


回答1:


Try this, it works for me.. :)

  public void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  {
        ListBox listBox = sender as ListBox;

        if (listBox != null && listBox.SelectedItem != null)
        {
            // do work
        }

        listBox.SelectedIndex = -1;
  }



回答2:


As Thierry asked, why do you want the user to select the same item again?

If it is just this one edge case where you have one item that fills the list box, then I would ask, is the single item (or first item with multiple returned) selected by default? If so, try setting the IsSynchronizedWithCurrentItem property to False on the List Box. Without seeing code, it's hard to provide a better answer.

If there is code that runs every time a user selects an item, no matter if it's the same one, you may have a workflow issue. You may want to see if you can refactor the code in this area to change up the workflow.

If you cannot change the workflow with selecting an item, even it's the same one, you may need to make each item in the list box a Button with the button's control template changed to that of a Textblock. This will allow you to bind to the Command property and know specifically which item was clicked on by the user.




回答3:


If you're using a ListBox to do something like navigation, it makes sense that you'd want the user to be able to select an item more than once in a row. Here's how you do it:

The 'problem' is simply that the ListBox notifies you of changes, and selecting the same item isn't a change. So invalidate it at the end of the method, and check for your invalidated state at the beginning.

public void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
   var lb = (ListBox)sender;
   if (lb.SelectedIndex == -1) return;

  //your selection logic here

   lb.SelectedIndex = -1;
}


来源:https://stackoverflow.com/questions/12150575/select-an-item-two-or-more-times

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