ListBox not highlighting selection on tab change

2019-07-15 07:39发布

问题:

I'm currently trying out C# and WPF for the first time.

I have a window with two tabs, tabA and tabB. Each tab has a list box (they are almost identical), tabA has listboxA and tabB has listboxB. When an item in a list box is selected, some information about the item is shown, so that I know that it is selected.

On a certain event E, I want an item in listboxA or listboxB to be highlighted and selected, which one is determined by the logic in my application.

Scenario A is that I am currently on tabA. When E occurs, an item in listboxA is chosen. I call listboxA.Focus(), and then listboxA.SelectedItem = item. This works fine. item is selected, so the information about the item is shown, and the item is highlighted in the list.

Scenario B, where I have my problem, is that I am currently on tabA. When E occurs, an item in listboxB is chosen. I call tabControl.SelectedItem = tabB to switch the tab, which works fine. As in Scenario A, I call listboxB.Focus() and then listboxB.SelectedItem = item. The item is selected, because the information about the item is shown, but, here's the thing: The item is not highlighted in the list box.

This also happens when changing from tabB to tabA. It always happens when I change the tab, but if I stay in the same tab the highlight works fine.

Does anyone know if there's anything else I need to do to give the list box the focus after changing the tab, apart from calling Focus()?

回答1:

WPF has focus scopes, the list box may be focused inside its scope but the scope itself if may not be focused. Alternatively the list box could have focus but it contains a separate scope for its items which would need to be focused.