处理在运行时从dll加载的WPF用户控件中的路由事件

时间:2015-02-13 19:30:45

标签: c# wpf wpf-controls

我有一个WPF控件库,我从主应用程序成功加载其程序集并显示我想要的用户控件。问题是我想为usercontrol处理键盘路由事件,但似乎消息永远不会到达它。建议:

我的情景 主应用程序窗口xaml:

<Window x:Class="Apollo.Clock.UI.ClockWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         ResizeMode="NoResize" WindowState="Maximized">
    <Grid>     
        <StackPanel x:Name="MainContainer"></StackPanel>
    </Grid>
</Window>

从主应用程序窗口加载用户控件:

UserControl myControl = null;
Assembly asm = Assembly.LoadFrom("AppUI.WPF.dll");
Type[] tlist = asm.GetTypes();
foreach (Type t in tlist){
    if (t.FullName == "DefaultSkin"){
        myControl = Activator.CreateInstance(t) as UserControl;
        MainContainer.Children.Add(myControl);
        break;
    }
}

DefaultSkin xaml:

<UserControl x:Class="DefaultSkin"
Keyboard.PreviewKeyDown="Window_PreviewKeyDown">

DefaultSkin.cs

private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
            e.Handled = true;
            //more code
}

1 个答案:

答案 0 :(得分:0)

只有在按下用户控件内的某个键时才会处理该事件。

要设置焦点,您可以使用以下内容:

激活用户控件后处理IsVisibleChanged:

myControl.IsVisibleChanged += SetKeyboardFocus;

并拥有SetKeyboardFocus方法:

void SetKeyboardFocus(object sender, DependencyPropertyChangedEventArgs e)
{
  IInputElement inputElement = sender as IInputElement;
  inputElement.Focusable = true;
  Keyboard.Focus(inputElement);
}