2009-07-28 112 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); 
    } 
}