tags:

views:

54

answers:

1

I have a tab control with two tabs and a listbox which is common to both tabs. This listbox needs to be aligned inside the tab specific content. Therefore I don't place it outside of the tabs. I have an another list box on one of the tabs. When I select an item in the second listbox, the first list boxes selected item becomes blue, so I have 2 list boxes showen as the focused control at once. Is there a workaround for this WPF bug ? Here is a screenshot and the code.

alt text

using System.Windows;
using System.Windows.Controls;

namespace WpfApplication3
{
    partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        void TabControl_SelectionChanged(
            object sender, SelectionChangedEventArgs e)
        {
            var parent = listBox.Parent as Panel;
            parent.Children.Remove(listBox);
            var panel = tabControl.SelectedIndex == 0 ? panel1 : panel2;
            panel.Children.Add(listBox);
        }
    }
}

<Window x:Class="WpfApplication3.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <TabControl Name="tabControl"
                SelectionChanged="TabControl_SelectionChanged">
        <TabItem Header="tab1">
            <StackPanel Name="panel1">
                <ListBox>
                    <ListBoxItem>click me second</ListBoxItem>
                    <ListBoxItem>item</ListBoxItem>
                </ListBox>
                <ListBox Name="listBox">
                    <ListBoxItem>click me first</ListBoxItem>
                    <ListBoxItem>item</ListBoxItem>
                </ListBox>
            </StackPanel>
        </TabItem>
        <TabItem Header="tab2">
            <StackPanel Name="panel2"/>
        </TabItem>
    </TabControl>
</Window>
+1  A: 

Hi the problem is that your tab controls selected event will fire when you click on the shared listbox, which brings in the instance of the list box that has focus in the other tab. Its actually not really a bug. It is doing exactly what you told it to do.

Change your code in your event handler to :

if (e.Source is TabControl)
{
   var parent = listBox.Parent as Panel;
   parent.Children.Remove(listBox);
   var panel = tabControl.SelectedIndex == 0 ? panel1 : panel2;
   panel.Children.Add(listBox);
}

That will stop the undesirable focused behaviour you were seeing.

Steve Psaltis