Today, I picked another new feature of Silverlight 4, namely the programmatic access to and from the clipboard in Silverlight 4.
Silverlight 4 has the ability to copy text to the clipboard, check if there is text available on the clipboard and paste the text from the clipboard back to the Silverlight application. To support this, it has 3 static methods available on the newly added ClipBoard class:
- Clipboard.SetText()
- Clipboard.ContainsText()
- Clipboard.GetText()
Let’s look at using these in a sample. Below we see the interface of the basic text editing application, containing 2 RichTextArea controls.
When clicking on the left button, we check if there’s some text selected in the left RichTextArea control. As said, this is done through the use of the static SetText() method on the ClipBoard class. Note that any interaction with the Clipboard class can only happen after a user-initiated action, such as clicking a Button.
private void CopyButton_Click(object sender, RoutedEventArgs e)
{ if (CopyTextArea.Selection.Text != string.Empty)
{ WarningTextBlock.Text = string.Empty;
Clipboard.SetText(CopyTextArea.Selection.Text);
}
else
{ WarningTextBlock.Text = "Select some text first";
}
}
This call is supported both in-browser and out-of-browser. There’s a difference though. When accessing the clipboard from an in-browser application, a warning will be shown to the user, asking if the action to the clipboard is trusted.
If we however make our application a trusted application by requiring elevated permissions when running out-of-browser, it will no longer display this prompt (we looked at elevating permissions yesterday).
When we want to paste in the text using the paste button, we can use the 2 other before mentioned methods, like so:
private void PasteButton_Click(object sender, RoutedEventArgs e)
{ if (Clipboard.ContainsText())
{ PasteTexArea.Selection.Text = Clipboard.GetText();
}
else
{ WarningTextBlock.Text = "No text exists on the clipboard";
}
}
In the current beta, we can only copy text to and from the clipboard. Objects such as images are not supported at this point!
The complete code for this sample can be found here: SilverlightClipboard.zip (61.65 KB)