简体   繁体   English

列表框中的selectedItem和焦点WPF

[英]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. 我在一个窗口中有2个listBoxes,一个挨着另一个,并带有将项目从一个listBox复制到另一个的按钮。 when an item from the first listBox is selected the copy button gets enabled, and remove button gets disabled. 当从第一个listBox中选择一项时,将启用“复制”按钮,并禁用“删除”按钮。 when i choose an item for the second listBox the copy button gets disabled, and remove button gets enabled. 当我为第二个listBox选择一个项目时,复制按钮被禁用,而删除按钮被启用。

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. 当listBox失去焦点时将所选项目设置为null无效,因为我需要选择的项目。 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. 我需要找到一种方法来在listBox获得焦点时重新选择选定的项目,或者只是触发选定项目更改的偶数。 any suggestions? 有什么建议么?

You can try the ListBox.LostFocus Event and set the SelectedItem Property to null. 您可以尝试ListBox.LostFocus事件,并将SelectedItem属性设置为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. 使用ListBox.GotFocus事件检查是否存在SelectedItem,存储索引,删除SelectedItem,然后使用存储的索引重置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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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