I have a TabControl with two TabItems 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 ListBox on one of the tabs. When I select an item in the second ListBox, the first ListBox‘s SelectedItem becomes blue, so I have 2 ListBoxes showen as the focused control at once.
Is there a workaround for this WPF bug? Here is a screenshot and the code:
alt text http://img85.imageshack.us/img85/871/2focusedcontrols.png
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>
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 :
That will stop the undesirable focused behaviour you were seeing.