
A detailed overview of Silverlight 4 innovations

- Printing from applications
- Handling right mouse clicks and wheel movements
- Work with webcam and microphone
- Work with the clipboard
- Trusted Application Features
- Interaction with COM Objects
- and much more…
Development tools
Visual Studio 2010 introduced the full Silverlight visual interface designer. Now you can edit the interface for applications on Silverlight versions 3 and 4. Implemented data binding support.

In addition, VS2010 for WCF RIA Services introduced an advanced editor with support for the DomainSource class as a Data Source.
And thanks to multi-targeting, in VS2010 you can simultaneously develop applications on Silverlight versions 3 and 4.
Video: Support for RIA Services in Visual Studio 2010
Printing from Silverlight (Printing API)
One of the most requested innovations has been client-side printing support. Silverlight 4 introduced such an API.
Code example:
private void PrintAll_Click(object sender, RoutedEventArgs e)
{
// инициализация нового PrintDocument
PrintDocument docToPrint = new PrintDocument();
// установка названия для отображения в очереди печати
docToPrint.DocumentName = "Entire Screen Sample";
// подготовка к печати
docToPrint.StartPrint += (s, args) =>
{
ActivityDisplay.IsActive = true;
};
// установка объекта для печати
docToPrint.PrintPage += (s, args) =>
{
args.PageVisual = this.StackOfStuff;
};
// завершение подготовки к печати
docToPrint.EndPrint += (s, args) =>
{
ActivityDisplay.IsActive = false;
};
// зупуск печати
docToPrint.Print();
}
As you can see above, it is possible to add pre- and postcodes to prepare for printing. PrintPage is a field in which the developer can set the interface element to be printed. It can be an existing element of the visual tree or something created in virtual memory.
Video and Code Examples: Printing API
Right Click Processing
Is it necessary to make a context menu in the application? Now, in addition to the MouseLeftButtonUp / Dow events, MouseRightButtonUp / Down events have appeared. This allows the developer to configure the execution of any code when clicking the mouse buttons, whether it is a control command in the game or opening a context menu.
Code example:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
// добавление выполнения функций при нажатии правой кнопки мыши
ChangingRectangle.MouseRightButtonDown += new MouseButtonEventHandler(RectangleContextDown);
ChangingRectangle.MouseRightButtonUp += new MouseButtonEventHandler(RectangleContextUp);
}
void RectangleContextUp(object sender, MouseButtonEventArgs e)
{
// создание контекстного меню и его показ
ColorChangeContextMenu contextMenu = new ColorChangeContextMenu(ChangingRectangle);
contextMenu.Show(e.GetPosition(LayoutRoot));
}
void RectangleContextDown(object sender, MouseButtonEventArgs e)
{
// по-умолчанию комнекстное меню должно быть скрыто
e.Handled = true;
}
}
This source code is a blank for adding a context menu to a Silverlight 4 application. The result will look like this:

Video and code examples: Processing the right mouse button
Webcam and Microphone Access
Need access to a webcam and / or microphone? In Silverlight 4, this can be done. With a few lines of code, a developer can ask the user for permission to access their video or audio capture device.
Sample code for requesting permission:
// запрос разрешения у пользователя и показ изображения
if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
{
_captureSource.Start();
}
Example code for capturing an image:
if (_captureSource != null)
{
_captureSource.Stop(); // остановка устройства захвата
// установка устройств захвата
_captureSource.VideoCaptureDevice = (VideoCaptureDevice)VideoSources.SelectedItem;
_captureSource.AudioCaptureDevice = (AudioCaptureDevice)AudioSources.SelectedItem;
// создание кисти
VideoBrush vidBrush = new VideoBrush();
vidBrush.SetSource(_captureSource);
WebcamCapture.Fill = vidBrush; // закраска области этой кистью =)
// запрос разрешения у пользователя и показ изображения
if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
{
_captureSource.Start();
}
}
A simple webcam photography API has also been added:
private void TakeSnapshot_Click(object sender, RoutedEventArgs e)
{
if (_captureSource != null)
{
// захват текучего кадра и добавление его в коллекцию
_captureSource.AsyncCaptureImage((snapImage) =>
{
_images.Add(snapImage);
});
}
}
You can read more about this in Russian in the article on the Habr “ Working with a web camera and microphone in Silverlight 4 ” by Sergey Pugachev WizardBox .
Video and Code Examples: Webcam and Microphone Support
Mouse wheel support
In previous versions of Silverlight, some auxiliary classes, for example, from DeepZoom, had to be used to handle mouse wheel events. In the fourth version, the corresponding API was added.
Code example:
// привязка события
myRectangle.MouseWheel += new MouseWheelEventHandler(RectangleZoom);
void RectangleZoom(object sender, MouseWheelEventArgs e)
{
// какой-либо код
}
As you can see, you can easily bind the mouse wheel event handling for a specific element.
Video and Code Examples: Handling Mouse Wheel Events
RichTextArea Element
One of the innovations requested by users was an interface element with editable rich text (support for bold, italics, different sizes, colors, etc.). Using RichTextArea, now you can get such an element.
Here's what a RichTextArea might look like:

Video and code examples: RichTextArea element
Clipboard API
Silverlight 4 added a simple clipboard API. It works on all platforms supported by Silverlight.
Code example:
Clipboard.SetText("Некоторый текст в буфере обмена");
This code shows the ability to write some text to the operating system clipboard from a Silverlight application.
The GetText () method returns the text contained in the buffer, and ContainsText () determines whether the text is currently stored in the buffer.
Video and Code Examples: Accessing the Clipboard
Clipboard.SetText("Некоторый текст в буфере обмена");
Display an HTML document using a WebBrowser element
When we work on the web, we almost always have to deal with HTML documents. In Silverlight 4, it became possible to display HTML documents in the application interface. To do this, use the WebBrowser element, the HTML code into which you can load both from the string variable and from the remote page by URL.
Sample Code (XAML):
Code Example (C #):
MyBrowserControl.NavigateToString("Example HTML");
Here's a picture of an example where a Silverlight application displays an HTML document with a YouTube player on Flash:

Alternatively, you can use the HtmlBrush brush to fill in any interface elements.
Video and Code Examples: Displaying HTML Documents in Silverlight
Trusted Applications
Sometimes an extrabrowser Silverlight application requires elevated permissions. In the fourth version, it became possible to request elevated rights. This can be done in the application properties in VS:

As a result, when installing an extrabrowser application, a warning appears:

The following innovations show the possibility of trusted applications.
Access local files on a client computer
For reading / writing data from a user's computer, mechanisms such as OpenFileDialog (for reading) and SaveFileDialog (for writing) are usually used. Silverlight 4 introduced direct access to the user's local files in My folders. These are “My Documents”, “My Video”, “My Music”, etc. On MacOS X, these are directories like "/ users / username / Videos".
To get the file path, you need to use the Environment namespace.
Code example:
private void EnumerateFiles(object sender, RoutedEventArgs e)
{
// создание списка для имен файлов
List videosInFolder = new List();
// используя Directory API,
// используя SpecialFolder API, получаем путь к папке "Мое видео"
var videos = Directory.EnumerateFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos));
// перечисляем файлы
foreach (var item in videos)
{
videosInFolder.Add(item);
}
// привязываем данные
VideoFileListing.ItemsSource = videosInFolder;
}
Extended rights are required (trusted application).
Video and Code Examples: Accessing Local Files
COM interoperability
Does the application need to do interaction with a peripheral device that provides only a COM interface? Or do you need to work with Office applications? Using the ComAutomationFactory API in a Silverlight 4 application, you can create and interact with COM objects.
Sample code (interaction with Excel):
// создание экземпляра Excel
dynamic excel = ComAutomationFactory.CreateObject("Excel.Application");
excel.Visible = true; // включение его видимости для пользователя
// добавление книги
dynamic workbook = excel.workbooks;
workbook.Add();
dynamic sheet = excel.ActiveSheet; // получение активного листа
Extended rights are required (trusted application).
Video and code examples: Access to COM objects in trusted applications
Notification APIs
Need a convenient mechanism for notifying users? Silverlight 4 introduced the ability to display pop-up notifications next to the tray.
Using NotificationWindow in Silverlight, you get a simple or custom notification mechanism for your application.
Code example:
private void CustomNotificationButton_Click(object sender, RoutedEventArgs e)
{
// создание окна уведомления
NotificationWindow notify = new NotificationWindow();
notify.Height = 74;
notify.Width = 329;
// создание содержимого этого окна
CustomNotification custom = new CustomNotification();
custom.Header = "Sample Header";
custom.Text = "Hey this is a better looking notification!";
custom.Width = notify.Width;
custom.Height = notify.Height;
// установка этого содержимого
notify.Content = custom;
// показ уведомления
notify.Show(4000);
}
Here's what the NotificationWindow element might look like:

Notifications can only be used in applications outside the browser.
You can read more about this in Russian in an article on the Habré " Silverlight 4: NotificationWindow " jeje .
Video and Code Examples: Notification Window API
Web Request Authentication
In Silverlight 4, it is possible to transmit NetworkCredential information using the ClientHttp stack, which was introduced in Silverlight 3. For example, to transfer a username / password to a service, you can do this:
// NetworkCredential passing is available in ClientHttp networking stack
WebRequest.RegisterPrefix("http://", System.Net.Browser.WebRequestCreator.ClientHttp);
WebClient myService = new WebClient();
myService.Credentials = new NetworkCredential("someusername", "somepassword");
myService.UseDefaultCredentials = false; // Иначе будут использованы значения по-умолчанию
myService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(OnResultCompleted);
myService.DownloadStringAsync(new Uri(http://somewebsite.com/authenticatedservice));
Video and Code Examples: Web Request Authentication
Cross Domain Changes
If your Silverlight 4 application operates in an elevated privilege mode (trusted application), then to work with web services from another domain, you no longer need to use the clientaccesspolicy.xml or crossdomain.xml files.
Video and Code Examples: Cross-Domain Requests in Trusted Applications
Full keyboard access in full-screen mode
If your Silverlight application runs in full screen (IsFullScreen = ”true”), only limited keyboard input was available to you. In trusted applications on Silverlight 4 in full screen mode, keyboard input for elements such as TextBox and others is fully supported.
Extended rights are required (trusted application).
Text trimming
The TextBlock element has a new property called TextTrimming, which allows it to be set to a WordElipse value. When this is done, any text that does not fit in the width of the element will be cut off, and instead of its not shown part there will be an ellipsis.
Code example:
Text="The quick brown fox jumped over the tall white fence"
TextTrimming="WordEllipsis" Width="120" />
It will look like this:

Right-to-left spelling support
If your application needs right-to-left spelling support (RTL), you can use the new element attribute - FlowDirection.
Code example:
This is an inherited property.
Video and Code Examples: Bidirectional and Right-to-Left Writing Support
Using Silverlight as a container for drag-n-drop
Sometimes it’s convenient to simply drag and drop the file onto the application window to load it. You can use this script by setting the AllowDrop attribute for any interface element.
Code example:
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
// установка обработки событий перетаскиания
InstallButton.Drop += new DragEventHandler(InstallButton_Drop);
InstallButton.DragOver += new DragEventHandler(InstallButton_DragOver);
InstallButton.DragEnter += new DragEventHandler(InstallButton_DragEnter);
InstallButton.DragLeave += new DragEventHandler(InstallButton_DragLeave);
}
void InstallButton_Drop(object sender, DragEventArgs e)
{
IDataObject foo = e.Data; // обработка данных
}
It is very convenient to use, for example, when uploading files to the server.
Video and code examples: Using Silverlight as a container for drag-n-drop
Links to other materials and resources on Silverlight 4 can be found in the article on the Haber “ Silverlight 4 Beta is already available. What's inside? »Mikhail Chernomordikov mixen .
Blog Entry: Silverlight 4 What's New