2009-07-28 84 views
2

我有一個複雜的WPF窗口與TabControl。其中一個TabItem託管一個WindowsFormsHost,它託管一些舊的Windows窗體控件。設置WPF中承載的Windows窗體元素的焦點

當我導航到此選項卡時,我嘗試將焦點設置爲其中一個控件。 Keyboard.Focus()不起作用,因爲它需要一個IInputElement,舊窗體窗體控件不支持。所以,我自己調用了舊的Windows窗體控件的Focus()方法,但由於某種原因它不起作用。

我把代碼調用焦點()你能想到的每一個事件:

  1. 的TabControl的SelectionChanged事件
  2. 的TabItem的IsVisibleChanged在事件
  3. 的TabItem的GotFocus事件

無他們工作。任何人有任何想法?

感謝

回答

2

我的解決辦法:

private void TabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) 
{ 
    Dispatcher.BeginInvoke(() => 
     { 
      FormsControl.Focus(); 
      System.Windows.Input.Keyboard.Focus(ControlHost); 
      Dispatcher.BeginInvoke(() => FormsControl.Focus()); 
     });   
} 

public static class DispatcherExtensions 
{ 
    /// <summary> 
    /// Executes the specified delegate asynchronously on the thread the System.Windows.Threading.Dispatcher is associated with. 
    /// </summary> 
    /// <param name="dispatcher">System.Windows.Threading.Dispatcher</param> 
    /// <param name="a">A delegate to a method that takes no arguments and does not return a value, which is pushed onto the System.Windows.Threading.Dispatcher event queue.</param> 
    /// <returns>An object, which is returned immediately after Overload:System.Windows.Threading.Dispatcher.BeginInvoke is called, that represents the operation that has been posted to the System.Windows.Threading.Dispatcher queue.</returns> 
    public static DispatcherOperation BeginInvoke(this Dispatcher dispatcher, Action a) 
    { 
     return dispatcher.BeginInvoke(a, null); 
    } 
}