
This article contains a more detailed description of Silverlight 4 innovations, such as:
- Printing from applications
- Handling right mouse clicks and wheel movements
- Work with a webcam and microphone
- Work with clipboard
- Features of trusted applications
- Interacting with COM Objects
- and much more…
For most, provide code examples and images.
Development tools
In Visual Studio 2010 there is a complete visual interface designer Silverlight. Now you can edit the interface for applications on Silverlight versions 3 and 4. Implemented data binding support.

In addition, in VS2010 for WCF RIA Services, an advanced editor appeared 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: RIA Services Support in Visual Studio 2010Printing from Silverlight (Printing API)
One of the most requested innovations was support for printing on the client side. In Silverlight 4, this API appeared.
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 can be seen above, it is possible to add pre- and post-code for preparation for printing. PrintPage is a field into which a developer can install an interface element that needs to be printed. This may be an existing element of the visual tree or something created in virtual memory.
Video and code samples: Printing API')
Handling the right mouse button
In the application, you need to make a context menu? Now, in addition to the MouseLeftButtonUp / Dow events, MouseRightButtonUp / Down events have appeared. This allows the developer to customize the execution of any code when the mouse buttons are clicked, be it 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 an application on Silverlight 4. The result will look like this:
Video and Code Samples: Right-Click ProcessingAccess to webcam and microphone
Need access to a webcam and / or microphone? In Silverlight 4, this can be done. With a few lines of code, the developer can request the user permission to access his device video or audio capture.
Sample code for requesting permission:
//
if (CaptureDeviceConfiguration.AllowedDeviceAccess || CaptureDeviceConfiguration.RequestDeviceAccess())
{
_captureSource.Start();
}
Sample code for image capture:
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();
}
}
Also added a simple API for photographing using a webcam:
private void TakeSnapshot_Click( object sender, RoutedEventArgs e)
{
if (_captureSource != null )
{
//
_captureSource.AsyncCaptureImage((snapImage) =>
{
_images.Add(snapImage);
});
}
}
More details about this in Russian can be found in the article on Habré “
Working with a webcam and microphone in Silverlight 4 ” by Sergey Pugachev
WizardBox .
Video and code samples: Webcam and microphone supportMouse wheel support
In previous versions of Silverlight, you needed to use any auxiliary classes for handling mouse wheel events, for example, from DeepZoom. 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 to a specific item.
Video and code samples: Mouse wheel event handlingRichTextArea Element
One of the innovations requested by users was an interface element with editable rich text (support for bold, italic, different sizes, colors, etc.). Using RichTextArea, you can now get such an element.
Here’s what RichTextArea might look like:
Video and code samples: RichTextArea elementClipboard API
A simple clipboard API has been added to Silverlight 4. 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 text is currently stored in the buffer.
Video and code samples: Access to clipboardClipboard.SetText( " " );
Displaying an HTML Document Using the 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 in which you can download both from a string variable or from a remote page by URL.
Sample Code (XAML):
< WebBrowser x:Name ="MyBrowserControl" Width ="800" Height ="600" />
Code Sample (C #):
MyBrowserControl.NavigateToString( "<div style='color:red;width:100;height:100'><b>Example HTML</b></div>" );
Here is an example of where the Silverlight application displays an HTML document with a YouTube player in Flash:

In addition, you can use the HtmlBrush brush to fill in arbitrary interface elements.
Video and code samples: Displaying HTML documents in SilverlightTrusted Applications
Sometimes a non-browser Silverlight application requires elevated privileges. In the fourth version, it became possible to request elevation rights. This can be done in the properties of the application in VS:

As a result, a warning will appear when installing an out-of-browser application:

The following innovations show the possibility of trusted applications.
Access to local files on the client computer
For reading / writing data from the user's computer, mechanisms such as OpenFileDialog (for reading) and SaveFileDialog (for writing) are usually used. Silverlight 4 now has direct access to the user's local files in the “My” folders. These are “My Documents”, “My Video”, “My Music”, etc. On MacOS X, these are directories of the type “/ users / username / Videos”.
To get the path to the files, you must use the Environment namespace.
Code example:
private void EnumerateFiles( object sender, RoutedEventArgs e)
{
//
List < string > videosInFolder = new List < string >();
// 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 permissions required (trusted application).
Video and code samples: Access to local filesCOM communication
Does the application need to make 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 permissions required (trusted application).
Video and code samples: Access to COM objects in trusted applicationsAPI pop-up notifications (Notification API)Need a convenient user notification mechanism? Silverlight 4 now has the ability to display pop-up notifications next to the tray.
Using Silverlight's NotificationWindow, you get a simple or customizable 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 is what the NotificationWindow element might look like:

Notifications can only be used in applications outside the browser.
In more detail about it in Russian it is possible to read in article on Habré "
Silverlight 4: NotificationWindow "
jeje .
Video and code samples: Notification Window APIWeb Request Authentication
In Silverlight 4, it is possible to transfer NetworkCredential information using the ClientHttp stack, which was introduced in Silverlight 3. For example, to transfer the login / password to the 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 Samples : Web Request AuthenticationChanges in cross-domain work
If your Silverlight 4 application is running in elevated privileges (trusted application), then to work with web services from another domain, you no longer need to use the files “clientaccesspolicy.xml” or “crossdomain.xml”.
Video and code samples: Cross-domain requests in trusted applicationsFull keyboard access in full-screen mode
If your Silverlight application is running 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 is fully supported for elements like TextBox, etc.
Extended permissions required (trusted application).
Text clipping
The TextBlock element has a new property called TextTrimming, which allows it can be set to WordElipse. When this is done, any text that does not fit the width of the element will be cut off, and instead of its unrevealed part there will be ellipsis.
Code example:
< TextBlock HorizontalAlignment ="Left" VerticalAlignment ="Top"
Text ="The quick brown fox jumped over the tall white fence"
TextTrimming ="WordEllipsis" Width ="120" />
It will look like this:

Right-to-left writing support
If your application requires support for right-to-left (RTL) writing, you can use the new element attribute, FlowDirection.
Code example:
< StackPanel HorizontalAlignment ="Center" VerticalAlignment ="Center" x:Name ="ControlSamples" >
< TextBlock FlowDirection ="LeftToRight" Foreground ="White" Text ="BiDi and RTL Sample" FontSize ="20" Margin ="20" />
< RichTextArea TextWrapping ="Wrap" Width ="600" Height ="150" ></ RichTextArea >
< TextBlock FontSize ="24" Foreground ="White" Text ="قفز الثعلب البني السريع فوق الكلب الكسول." />
< ListBox >
< ListBox.Items >
< ListBoxItem Content ="قفز الثعلب البني السريع فوق الكلب الكسول." />
< ListBoxItem Content ="Option 1" />
< ListBoxItem Content ="Option 2" />
< ListBoxItem Content ="Option 3" />
< ListBoxItem Content ="Option 4" />
</ ListBox.Items >
</ ListBox >
</ StackPanel >
This is an inherited property.
Video and code samples: Support for bidirectional text and writing from right to leftUsing the Silverlight application as a container for drag-n-drop
Sometimes it is convenient to simply drag the file onto the application window to load it. You can use this script by setting the AllowDrop attribute for any element of the interface.
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-dropLinks to other materials and resources on Silverlight 4 can be found in the article on Habré “
Silverlight 4 Beta is already available. What's inside? »Mikhail Chernomordikov
mixen .
My blog entry:
Silverlight 4 Innovation Overview