[英]Handle Routed Events in WPF user control loaded from a dll at runtime
I have an WPF control library, I successfully load its assembly from main app and show the user control I want. 我有一个WPF控件库,我从主应用程序成功加载其程序集并显示我想要的用户控件。 The problem is that I want to handle keyboard routed event for usercontrol but it seems that the message never reach to it.
问题是我想为usercontrol处理键盘路由事件,但似乎消息永远不会到达它。 Advice?:
忠告?:
My scenario Main App Window xaml: 我的场景主应用程序窗口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>
Loading user control from main app windows: 从主应用程序窗口加载用户控件:
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: DefaultSkin xaml:
<UserControl x:Class="DefaultSkin"
Keyboard.PreviewKeyDown="Window_PreviewKeyDown">
DefaultSkin.cs DefaultSkin.cs
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
e.Handled = true;
//more code
}
It will only handle the event in case you press a key inside the usercontrol. 只有在按下usercontrol中的某个键时,它才会处理该事件。
To set the focus you can use the following: 要设置焦点,您可以使用以下内容:
after Activiting the user control handle the IsVisibleChanged: 激活用户控件后,IsVisibleChanged:
myControl.IsVisibleChanged += SetKeyboardFocus;
and have SetKeyboardFocus method: 并有SetKeyboardFocus方法:
void SetKeyboardFocus(object sender, DependencyPropertyChangedEventArgs e)
{
IInputElement inputElement = sender as IInputElement;
inputElement.Focusable = true;
Keyboard.Focus(inputElement);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.