简体   繁体   中英

selectedItem in listbox and focus wpf

i have 2 listBoxes in a window, one next to the other, with buttons to copy items from one listBox to the other. when an item from the first listBox is selected the copy button gets enabled, and remove button gets disabled. when i choose an item for the second listBox the copy button gets disabled, and remove button gets enabled.

when you select an item in one of the listBoxes the buttons change with no problem, after the listBox lost focus and you choose the same item that was selected the buttons dont change back.

i understand the problem is that the event of selected item changed will not fire, beacuse the selected item did not change.

setting the selected item to null when the listBox loses focus was not usefull beacuse i need the selcted item. i need to find a way to reselect the selected item when the listBox gains focus, or just fire the even of selected item changed. any suggestions?

You can try the ListBox.LostFocus Event and set the SelectedItem Property to null.

private void ListBox_LostFocus(object sender, RoutedEventArgs e)
{
    ((ListBox)sender).SelectedItem = null;
}

Use the ListBox.GotFocus event check if there is a SelectedItem, store the index, remove the SelectedItem and use the stored index to reset the SelectedItem. Something like this

private void ListBox_GotFocus(object sender, RoutedEventArgs e)
{
    ListBox lb = (ListBox)sender;
    if(lb.SelectedItem != null )
    {
        int index = lb.SelectedIndex;
        lb.SelectedItem = null;
        lb.SelectedIndex = index;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM