WPF弹出标签关键错误 [英] WPF Popup tab key bug

查看:137
本文介绍了WPF弹出标签关键错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有列表框和按钮的WPF弹出控件.当我单击Button时,它应该被禁用.问题是,当我禁用按钮时,Tab键会从弹出窗口中消失.在将Button的IsEnabled设置为false之后,我尝试将焦点设置到ListBox上,但这没有用.那么,如何将选项卡焦点设置到Popup控件内的ListBox上?

I have a WPF Popup control with a ListBox and a Button in it. When I click the Button, it should become disabled. The problem is, that when I disable the Button, the Tab key goes out from the Popup. I tried to set the focus to the ListBox, after I set the Button's IsEnabled to false, but that did not work. So, how can I set the tab focus to the ListBox inside the Popup control ?

这是我的代码.

Window1.xaml:

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:

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);
        }
    }
}

这是屏幕截图:

替代文本http://img11.imageshack.us/img11/6305/popuptabkey .png

以后的修改:

我找到了一种解决方法,那就是延迟FocusListBox();调用,如下所示:

I've found a workaround, that is to delay the FocusListBox(); call as below:

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

推荐答案

您需要通过设置

这将使焦点不会移回包含元素中的控件.

This will keep the focus from moving back out to controls within the containing element.

这篇关于WPF弹出标签关键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆