C# – WPF Maintain ListBox selection when tab changes

clistboxmvvmwpfxaml

I have a TabControl where the content of each TabItem is a master-details view.

For the master, I'm using a listbox whose ItemsSource is bound to a collection in my ViewModel. Selecting an item from the list displays that particular item's details in a grid off to the side.

When I switch to another tab and then back to the original tab, the listbox selection seems to be lost.

What can I do to maintain the listbox selections in each tab when the tab selection changes?

In normal use the end users will need to 'set up' the detail views the way they like for a particular situation, and then cycle through the tabs occasionally to check on each system (each tab provides details for machinery on a different product line).

The TabControl looks like this:

<TabControl 
    ItemsSource="{Binding DiagCards}"
    ContentTemplate="{StaticResource DiagCardViewTemplate}"
    SelectedItem="{Binding SelectedDiagCard}" />

The View for each TabItem has a ListBox that looks like this:

<ListBox
   ItemsSource="{Binding DiagCard.DevicesDetected}" 
   SelectedItem="{Binding SelectedDevice}"/>

The details are displayed in the TabItem using a ContentControl:

<ContentControl
   Content="{Binding SelectedDevice}"
   ContentTemplateSelector="{StaticResource SelectedDeviceTemplateSelector}"/>

I should note that a simple test using hard-coded TabItems and ListBoxes does seem to maintain the selection when the tab changes:

    <TabControl>
        <TabItem Header="tab 1">
            <ListBox>
                <ListBoxItem>
                    <TextBlock Text="item 1-1"/>
                </ListBoxItem>
                <ListBoxItem>
                    <TextBlock Text="item 1-2"/>
                </ListBoxItem>
            </ListBox>
        </TabItem>
        <TabItem Header="tab 2">
            <ListBox>
                <ListBoxItem>
                    <TextBlock Text="item 2-1"/>
                </ListBoxItem>
                <ListBoxItem>
                    <TextBlock Text="item 2-2"/>
                </ListBoxItem>
            </ListBox>
        </TabItem>
    </TabControl>

Update: I set IsSynchronizedWithCurrentItem="True" on the listbox and all seems to be well.

Best Answer

Based on your comment I would guess something is changing in your viewmodel to remove the selected item. Can you set a breakpoint on the setter of SelectedDevice and check the call stack?

To test that can you remove the SelectedItem={} code and see if it stays selected when you change tabs?

To answer more completely I would need to see more code.

Related Topic