Pergunta

Eu tenho um controle pop -up WPF com uma caixa de listagem e um botão nele. Quando eu clico no Button, deve ficar desativado. O problema é que, quando desabilito o botão, a tecla da guia sai do pop -up. Eu tentei definir o foco na caixa de listagem, depois de definir o botão IsEnabled Para falso, mas isso não funcionou. Então, como posso definir o foco da guia para a caixa de listagem dentro do controle pop -up?

Aqui está o meu código.

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

E aqui está uma captura de tela:

ALT TEXTO http://img11.imageshack.us/img11/6305/popuppabkey.png

Editar posterior:

Eu encontrei uma solução alternativa, isto é, para adiar o FocusListBox(); Ligue para abaixo:

Dispatcher.BeginInvoke(new Action(FocusListBox), DispatcherPriority.Input);
Foi útil?

Solução

Você precisa definir um escopo de foco explícito, definindo o FocusManager.isfocusscope Propriedade no pop -up:

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

Isso impedirá que o foco volte para os controles dentro do elemento contendo.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top