昨天说Silverlight User Control不能接收键盘消息,但是Page.xaml是可以接收键盘消息。既然Page能够接收键盘消息,那么我们就可以用Page来接收消息,然后想办法转发给User Control页面就行了。一个简单的实现方法就是利用C#中的delegate来实现。

简单的例子如下:
1、先在Page.xaml.cs中声明一个delegate类型以及一个该类型的变量,其参数和KeyboardEventHandler的参数一样,这样就可以直接把事件传过去了;

public delegate void SubKeyBoardEventHandler(object sender, KeyboardEventArgs e);
public SubKeyBoardEventHandler subKeyHandler = null;

2、在Page.xaml.cs中监听键盘消息:

this.KeyDown += new KeyboardEventHandler(Page_KeyDown);

3、这个键盘事件Handler要写成这样:

void Page_KeyDown(object sender, KeyboardEventArgs e)
{
if (subKeyHandler != null)
{
subKeyHandler(sender, e);
}
}

4、在User Control页面中,需要在构造函数里把Page实例传过去,这样就能给subKeyHandler赋值了:

public UC(Page pc)
{
System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream(“TestKeyEvent.UC.xaml”);
this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());

pc.subKeyHandler = testKeyHandler;
}

5、testKeyHandler如下:

void testKeyHandler(object sender, KeyboardEventArgs e)
{
//here is your code
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.