WPF弹出选项卡密钥错误

时间:2009-10-19 23:37:36

标签: wpf popup focus tab-ordering

我有一个带有ListBox和Button的WPF Popup控件。当我点击Button时,它应该被禁用。问题是,当我禁用Button时,Tab键从Popup中退出。在我将Button的IsEnabled设置为false之后,我尝试将焦点设置为ListBox,但这不起作用。那么,如何将选项卡焦点设置为Popup控件中的ListBox?

这是我的代码。

Window1.xaml:

<Window x:Class="WpfApplication5.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">
    <StackPanel>
        <Button Name="openButton" Content="Open"/>
        <Popup Name="popup" Placement="Center">
            <StackPanel>
                <ListBox Name="listBox"/>
                <Button Name="newItemsButton" Content="New Items"/>
            </StackPanel>
        </Popup>
    </StackPanel>
</Window>

Window1.xaml.cs:

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

namespace WpfApplication5
{
    partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            openButton.Focus();
            listBox.ItemsSource = new string[] { "Item1", "Item2", "Item3" };
            listBox.SelectedIndex = 1;

            openButton.Click += delegate { popup.IsOpen = true; };
            popup.Opened += delegate { FocusListBox(); };
            newItemsButton.Click += delegate
            {
                newItemsButton.IsEnabled = false;
                FocusListBox();
            };
        }

        void FocusListBox()
        {
            var i = listBox.ItemContainerGenerator.ContainerFromIndex(
                listBox.SelectedIndex) as ListBoxItem;
            if (i != null)
                Keyboard.Focus(i);
        }
    }
}

这是截图:

alt text http://img11.imageshack.us/img11/6305/popuptabkey.png

稍后编辑:

我找到了一种解决方法,即延迟FocusListBox();来电,如下所示:

Dispatcher.BeginInvoke(new Action(FocusListBox), DispatcherPriority.Input);

1 个答案:

答案 0 :(得分:2)

您需要通过在弹出窗口中设置FocusManager.IsFocusScope property来定义显式焦点范围:

<Popup FocusManager.IsFocusScope="true">
  <!-- your content here -->
</Popup>

这将使焦点不再回到包含元素内的控件。