Andrej Tozon's blog

In the Attic


Countdown to Silverlight 3 #11: Writeable Bitmap

Want to create a new bitmap image in Silverlight? Want to capture a part of your application and use it as a brush? Silverlight has an answer for you – WriteableBitmap is a BitmapSource-derived class that you can manipulate in the runtime, either by rendering UI elements on it or by manipulating pixels manually. The example (below) will show how to capture a movie frame or an entry form, along with altering some pixels on the captured image – try moving your mouse over either of the captured images.

Run the application online

Source code below:

Countdown to Silverlight 3 #10: Animation easing

Doing non-linear animations with Silverlight 2 involved “playing” with key splines, and it took quite some time to get it right, even if using a tool like Expression Blend. Silverlight 3 puts some ease in this process by introducing the new, predefined, so-called easing functions, that can be applied to an animation to affect its state while progressing through time. It’s similar to what you could achieve with the splines, but without the fuss. The functions include some standard progressions (Circle, Cubic, Exponential, Quadratic, etc), with a couple of more interesting ones (Back, Elastic).

If the provided functions not enough for you, you can create your own function by creating a new class, deriving from the EasingFunctionBase class. I’ve created a “JerkyEase” animation, which is really a very simple linear animation, but with a random jerky-interrupty points to make it look… well, kind of underperformant. Totally useless, but it made it into the sample deck until I figure out something more usable.

Run the application online

Source code below:

Countdown to Silverlight 3 #9: Day 0 and updated sample deck

After a week of spending my holidays, enjoying the sun and playing on the beach with my kids, it’s time to continue the Silverlight 3 countdown series… In the meantime, Silverlight 3 was officially released (it’s probably best to only reference the “Cream” of the SL3 release posts here, in case you missed all the fun, like I did).

I updated my Countdown sample application to match the SL3 RTW bits, with all the necessary changes, most of them having to do with OOB API changes (read more about SL2/SL3B breaking changes here). Visual Studio is now also providing a nice new settings screen for describing your OOB application.


I’ll continue adding more examples of SL3 new features in the future.

Congrats and thanks to everybody having their part in getting the Silverlight 3 release ready and out so soon after the initial release.

Run the updated application online[SL3RTW required]

Source code below:

Countdown to Silverlight 3 #8: Style inheritance

Silverlight 3 supports style inheritance through setting the BasedOn property. Although not as powerful as that in WPF, using this feature can significantly improve the maintainability of application styles – instead of duplicating several properties when creating similar styles, you can define one base style, set some common properties, then create a a derived style, inheriting those properties and adding new ones.

When defining a new style, the BasedOn property an be used to reference a base style, thus extending it with new properties. All you have to be careful about is to target the same type (or its derivate) as the base style. For example, you can’t create a new style, targeting a Button, if the base style targets a TextBox. You can, however, target a Button, if the base style targets a Button, ButtonBase, ContentControl, etc (ascendants of a Button). You can also overwrite property values, set in a base style – either in a derived style, or by setting it directly on a control.

The example below covers some of the mentioned scenarios.

Style inheritance

Run the application online

Source code below:

Countdown to Silverlight 3 #7: Navigation

Another powerful Silverlight 3 feature is navigation. The concept is very simple: provide a space on your main page, which you’ll later fill with custom content – pages. You’ll be able to navigate through these pages (by using browser’s Forward/Back buttons, directly access them and even provide custom parameters.

There’s a special project template in Visual Studio 2008 to create a Silverlight Navigation application and it provides a good start if you’re new with this feature – you’ll get a nice template to get you going, which you’ll be able to customize as you go forward.

There is one core control that you’ll need to enable this feature – System.Windows.Controls.Frame, which will host your pages by navigating to them. A Page is a special control, derived from UserControl, adding navigation capabilities.

I refactored my Silverlight 3 features application to a Navigation application, each sample being a separate page, accessible from a list of samples. I’ll continue to add new samples to this application in the future. I’ll try to maintain the main application (as well as the examples pages) to be as much MVVM-ish as possible, but without having to resort to any external dependencies.

A couple of things to note in the new, refactored application:

1. By using Element binding feature to bind the Frame Source to selected Url in the samples list, calls to Navigate() method aren’t required – binding does all the magic.

<ListBox x:Name="views"
           ItemsSource="{Binding Links, Source={StaticResource viewModel}}" ... />
<navigation:Frame Source="{Binding SelectedItem.Value, ElementName=views}" ... />

2. Passing custom parameters to a page. MergedResourceDictionaries page has been modified so it accepts a parameter of a theme to be applied to the sample form.

3. Uri mapping. Parameters for MergedResourceDictionaries can be passed in to the paged in a shorter form, thanks to the Uri mapper.

4. To prevent any mis-addressing of navigation pages, attach a handler to frame’s NavigationFailed event and handle those cases to spare your users from seeing some nasty popup windows, telling them they misspelled the url.

private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
e.Handled = true;
views.SelectedIndex = 0;

Silverlight 3 navigation feature greatly simplifies creation of modern, interactive web sites with multiple pages, where previous to SL3, ASP.NET was in lots of cases the first choice.

Additional reading

Run the sample online

Source code below:

Countdown to Silverlight 3 #6: System colors

With Silverlight 3, we now have access to system colors. If you need your new application to visually fit into the operating system it’s running on, simply inspect one of the static properties, provided by the new SystemColors class – System.HighlightColor for example, will tell you what color is used for highlighting the selection in ListBoxes.

The provided example (below) will enumerate all available system colors and display them on the screen. To test it, go to your Control Panel and change the color scheme, then restart the application.

image image
Windows Aero vs. High Contrast Black

Additional reading

Run the sample online

Source code below:

Countdown to Silverlight 3 #5: ChildWindow (Modal, Non-modal, Templated)

There are many controls being introduced in Silverlight 3; a lot of them were pulled from the Silverlight Toolkit (the idea is that for every new Silverlight version, Toolkit controls marked as stable are moved to the Silverlight core. I’m not sure how many new controls I’m going to cover in this series, but the ChildWindow definitely deserves a separate post and sample.

ChildWindow is a special control, which behaves like a dialog. By default, it is set up to display itself as a modal dialog and can be easily re-templated to give it a new look (included in the sample below).

There are three steps required to make the ChildWindow display as a non-modal (floating) window:

1. Create a copy of the default template and get rid of all animations, referencing the Overlay element. The overlay covers all area “behind” the child window and makes it look disabled. If you remove the Overlay element itself, the window will not be centered on the screen when invoked, so it’s best to keep it in, but somehow hide it.

<Grid x:Name="Overlay" Width="0" Height="0" />

2. This is a hack. ChildWindow disables the root element when invoked so you have to re-enable it when window is shown:

Control root = Application.Current.RootVisual as Control;
if (root != null)
root.IsEnabled = true;

3. This is a hack. ChildWindow also takes control of re-focusing the window when the root control gains the focus so we have to hack into the ChildWindow’s LostFocus event to take care of this:

protected override void OnLostFocus(RoutedEventArgs e)
LostFocus -= Delegate.CreateDelegate(typeof(RoutedEventHandler), this,
    "ChildWindow_LostFocus") as RoutedEventHandler;

Additional reading: (a better approach to non-modal window, also read the comments)

Run the sample below

Source code below:

Countdown to Silverlight 3 #4: Element binding

Binding to elements is yet another feature, known to WPF-ers since v1. Silverlight 3 now allows bindings between UI elements and their properties, without having to use other classes as a workaround. There are numerous cases of when to use such binding, mostly to automate user interface, starting from the basic example of connecting a TextBox to a Slider (also included in the sample below). The interesting point to this binding is that it also works two-way: the TextBox not only displays the current value of the Slider, entering a new value also updates the Slider.

To make the sample a bit more interesting, I included a new kind of panel, which stores the current mouse coordinates when moving it over the panel. I added two TextBoxes and bound them to the panel to display these coordinates. There’s also an ellipse, which… well, see for yourself ;)

Additional Reading

Run the sample online

Source code below:

Countdown to Silverlight 3 #3: Merged resource dictionaries

Coming from the WPF world, finding out that Silverlight lacked the feature of distributing application resources among separate files was one of those kick in a head moments. Well, not anymore. Silverlight 3, like its big brother WPF, now supports partitioning resources through merged dictionaries.

Merged resource dictionaries can be included as external files (build action = Content), as included resources (build action = Resource), or as referenced assembly resources (e.g. theming).

<ResourceDictionary Source="Themes/Theme1.xaml" />
<ResourceDictionary Source="Themes/Theme2.xaml" />

Merged resource dictionaries come in useful when:

  • providing different themes for the application (like in the sample below)
  • providing a new style/template for existing control
  • providing a style/template for a custom control

Run the sample online

Source code below:

Countdown to Silverlight 3 #2: Setting styles

Silverlight 3 is introducing a small, but very powerful feature: styles in Silverlight 3 can be set multiple times! For example, executing the following code in Silverlight 2 will throw a “catastrophic failure” exception on the second line:

textBox.Style = Application.Current.Resources["TextBoxStyle"] as Style;
textBox.Style = Application.Current.Resources["TextBoxStyle"] as Style;

Silverlight 3, on the other hand, won’t have any problems with setting control’s style the second, third or n-th time, if required.

To reset a control’s style, one can simply set it to null:

textBox.Style = null;

… or assign an empty style to it:

<Style x:Key="EmptyTextBoxStyle" TargetType="TextBox" />

Source code below: