2012-04-24 7 views

risposta

3

È possibile collegare agli eventi di anteprima tunneling:

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="350" Width="525" 
    PreviewGotKeyboardFocus="Window_PreviewGotKeyboardFocus" 
    PreviewLostKeyboardFocus="Window_PreviewLostKeyboardFocus"> 
.... 

In questo modo, come mostrato sopra, la finestra sarebbe stato notificato prima di tutti i discendenti quando uno dei discendenti ottiene o perde il focus della tastiera.

Leggi this per ulteriori informazioni.

+1

Sembra che questo metodo potrebbe portare a risultati errati a causa del fatto che si tratta di un evento di anteprima, e quindi il cambio di messa a fuoco potrebbe non avvenire. Ciò si verifica se un UIElement tra la finestra e l'elemento source ha contrassegnato l'evento come gestito. – Hank

+0

Sono d'accordo con @Hank. PreviewXxx non garantisce che cambierà effettivamente. La risposta di Vaccano è in realtà quella giusta. Nicolas ha anche un sostituto, anche se non è proprio la stessa cosa, visto che tutti gli attori della catena vengono avvisati grazie alla ricaduta degli eventi gestiti. – MarqueIV

5

È possibile aggiungere un gestore di eventi indirizzato alla finestra principale e specificare che si è interessati agli eventi gestiti.

mainWindow.AddHandler(
    UIElement.GotKeyboardFocusEvent, 
    OnElementGotKeyboardFocus, 
    true 
); 
+0

Ha funzionato perfettamente! Grazie molto! – Alexey

12

È possibile farlo in qualsiasi classe con questo:

//In the constructor 
EventManager.RegisterClassHandler(
     typeof(UIElement), 
     Keyboard.PreviewGotKeyboardFocusEvent, 
     (KeyboardFocusChangedEventHandler)OnPreviewGotKeyboardFocus); 

...

private void OnPreviewGotKeyboardFocus(object sender, 
             KeyboardFocusChangedEventArgs e) 
{ 

    // Your code here 

} 
0

Avere uno sguardo a come Microsoft grilletto CommandManager.RequerySuggested evento quando i cambiamenti di messa a fuoco: sottoscrivere InputManager.PostProcessInput evento.

ReferenceSource

semplice esempio:

static KeyboardControl() 
{ 
    InputManager.Current.PostProcessInput += InputManager_PostProcessInput; 
} 

static void InputManager_PostProcessInput(object sender, ProcessInputEventArgs e) 
{ 
    if (e.StagingItem.Input.RoutedEvent == Keyboard.GotKeyboardFocusEvent || 
     e.StagingItem.Input.RoutedEvent == Keyboard.LostKeyboardFocusEvent) 
    { 
     KeyboardFocusChangedEventArgs focusArgs = (KeyboardFocusChangedEventArgs)e.StagingItem.Input; 
     KeyboardControl.IsOpen = focusArgs.NewFocus is TextBoxBase; 
    } 
} 

Questo funziona anche in applicazioni multi-finestra.

Problemi correlati