开发者

A dynamically created list box's selected item becomes blue when another list box's selection is changed

I have a TabControl with two TabItems and a ListBox which is common to both tabs. This ListBox needs to be aligned inside th开发者_运维问答e 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 :

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜