Monday, October 13, 2008

Clipboard support in Silverlight 2

* UPDATE *
The demo now works with Silverlight 2 RTW and the ClipboardHelper has been added to the source of the SilverlightContrib project. It'll be in the next release.

By default, there is no clipboard support in Silverlight 2. Page Brooks, who is the project coordinator of the open source project SilverlightContrib I'm working on with a bunch of other developers (I feel really honered to work with them...), wanted to add this to the SilverlightContrib project as well so I decided to start off with a basic implementation.

You can create (limited) clipboard support in Silverlight by using Javascript and HTML DOM to read from, add to and clear the clipboard. Note that this will only work in Internet Explorer.

I created a class in which the following methods do the most important work:


public void SetData(string Value)
{
_window.Eval(string.Format("window.clipboardData.setData('text','{0}')", Value));
}

public string GetData()
{
this._currentValue = (string)_window.Eval("window.clipboardData.getData('text')");
return _currentValue;
}

public void ClearData()
{
_window.Eval("window.clipboardData.clearData()");
}


In the constructor of the class I create the possibility to add multiple UIElements as a parameter:


public ClipboardHelper(params UIElement[] UIElementsToCatchEventsOf)
{
if (UIElementsToCatchEventsOf != null)
{
foreach (UIElement element in UIElementsToCatchEventsOf)
{
element.KeyDown += new KeyEventHandler(UIElement_KeyDown);
element.KeyUp += new KeyEventHandler(UIElement_KeyUp);
}
}
}


By subscribing to the KeyUp and KeyDown event of the specific UIElement you can also add paste support to the elements. For example the Button:

private void UIElement_KeyUp(object sender, KeyEventArgs e)
{
if(e.Key == Key.Ctrl)
_ctrlPressed = false;
if (e.Key == Key.V && _ctrlPressed)
{
this.GetData();
if (sender.GetType() == typeof(Button))
{
Button buttonSender = (Button)sender;
buttonSender.Content = this.GetData();
}
}
}


You could also create your own implementation for ListBox and other elements. Be aware though that this will only work with items that can gain focus.


Watch the demo here

Download the project here