I thought I’d tackle one of the most obvious problems with Silverlight today, the lack of a text edit control. So I thought I’d share my first "toe wetting" in this.
First off I created simple Silverlight 1.1 project with a canvas and a TextBlock…
<Canvas x:Name="parentCanvas"
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="Page_Loaded"
x:Class="SilverlightProjectKeyEcho.Page;assembly=ClientBin/SilverlightProjectKeyEcho.dll"
Width="640"
Height="480"
Background="White"
>
<TextBlock x:Name="TextBlockEcho" Text="Hello there"></TextBlock>
</Canvas>
xmlns="http://schemas.microsoft.com/client/2007"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Loaded="Page_Loaded"
x:Class="SilverlightProjectKeyEcho.Page;assembly=ClientBin/SilverlightProjectKeyEcho.dll"
Width="640"
Height="480"
Background="White"
>
<TextBlock x:Name="TextBlockEcho" Text="Hello there"></TextBlock>
</Canvas>
I find it useful to always create something I can see by default.
Q1. How to accept keyboard input at all?
Well there is a trick to this. First off I used Intellisense in both the XAML and the code behind to create an event for KeyDown on the TextBlock, but I kept getting a (hidden) exception when running the code. After a quick look around the web I discovered that keyboard event can only be attached to the root canvas. I created a quick handler…
public void EchoKeyDown(object sender, KeyboardEventArgs e)
{
int keyCode = (char)e.PlatformKeyCode;
if (!e.Shift)
{
keyCode = keyCode + 32;
}
TextBlockEcho.Text += (char)keyCode;
}
{
int keyCode = (char)e.PlatformKeyCode;
if (!e.Shift)
{
keyCode = keyCode + 32;
}
TextBlockEcho.Text += (char)keyCode;
}
and I’ve got a very simple text echo. Now to tackle CTRL,SHIFT, Delete, arrow keys, etc, etc…
public partial class Page : Canvas
{
UserControl1 s;
public void Page_Loaded(object o, EventArgs e)
{
// Required to initialize variables
InitializeComponent();
s = new UserControl1();
Children.Add(s); —– Not works
}
public class UserControl1 : Control
{
public UserControl1()
{
System.IO.Stream s = this.GetType().Assembly.GetManifestResourceStream("SilverlightProject5.UserControl1.xaml");
FrameworkElement fe = this.InitializeFromXaml(new System.IO.StreamReader(s).ReadToEnd());
Canvas cv = fe.FindName("canvas");
cv.KeyDown += new KeyboardEventHandler(cv_KeyDown);
}
void cv_KeyDown(object sender, KeyboardEventArgs e)
{
}
}
if keydown event handler is added in usercontrol , chodren.add not works
What error do you get?