Andrej Tozon's blog

In the Attic


My “What’s new in Silverlight 4 demo” app

What’s new in Silverlight 4? Isn’t Silverlight 4, like, old news by now?

Well yes, as the matter of fact, this is one of those long overdue posts that have a hard time getting out. As I’ve been showing these demos since Silverlight 4 Beta came out, this is really the high time I release the source code… Especially when we’re looking to get a fresh preview of Silverlight 5 in the near future.

So here it is – the source code of my Silverlight 4 sample project.

You can also see the project live.

And the rundown of what you can expect to see in the demos:

Fluid layout : Layout states

The first thing you’ll notice when running the demo app is a few images finding it’s way on the screen from the left, sequentially, one by one, with a nice animation. This was done by using new layout states, found on the ListBoxItem. The new LayoutStates (BeforeLoaded, AfterLoaded, BeforeUnloaded) can be used to add a story to your ListBox items. With common ListBox, the effect of items just mysteriously appearing in the box can be confusing to the user, and the same goes for them suddenly disappearing from it. By using animation, you can tell the story of where they came from and why, as well as to where they go when they are removed. Or you just want to prettify your UI a bit. Whatever… Anyway, looking at the code for this reveals nothing really special – the items are simply added to the list:

MenuItems = new ObservableCollection<MenuItem>();

menuItems.Add(new MenuItem { Caption = "WB", ImageUri = new Uri("Assets/html.png", UriKind.Relative), DataContext = "WebBrowser" });
foreach (var videoDevice in CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices())
    menuItems.Add(new MenuItem { Caption = videoDevice.FriendlyName, ImageUri = new Uri("Assets/video.png", UriKind.Relative), DataContext = videoDevice });
menuItems.Add(new MenuItem { Caption = "RTB", ImageUri = new Uri("Assets/rtb.png", UriKind.Relative), DataContext = "RichTextBox" });
menuItems.Add(new MenuItem { Caption = "Paste", ImageUri = new Uri("Assets/paste.png", UriKind.Relative), DataContext = "Paste" });
menuItems.Add(new MenuItem { Caption = "CLS", ImageUri = new Uri("Assets/clear.png", UriKind.Relative), DataContext = "" });

Nothing special, but there are a couple of tricks: first, to make items appearing one by one, I’ve used a timer:

DispatcherTimer startTimer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(0.2)};
int menuItemCount = 0;
startTimer.Tick += (s, e) =>
                           if (menuItemCount >= menuItems.Count)

There is actually a better way of doing this now – Reactive Extensions, which I blogged about a couple of posts ago.

Second, I’ve used the BeforeLoaded and AfterLoaded layout states for animating the ItemsControlItems to transition from “non-existing” state to “loaded-and-visible" state. In other words, make them appear on their place in the ItemsControl through animation.

Third – what’s an ItemsControlItem? Out of the box, LayoutStates are only set on the ListBoxItem, if you want to use them on a plain ItemsControl, which also serves as a base for the ListBox, you have to create some kind of workaround, which includes a new class for your item container – ItemsControlItem. See the code for the example.

TextBlock Text trimming

In the menu which appears on the left when you start the app, you may or may not see the text in one on more boxes trimmed. This is achieved with a new property called TextTrimming. Set it to WordEllipsis to enable the trimming:


WebCam support and VideoBrush

In the menu code above you might’ve noticed the CaptureDeviceConfiguration.GetAvailableVideoCaptureDevices() enumeration loop – that’s how you enumerate your video-capable devices. Have many webcams plugged in? They’ll all show up in your menu – with the same icon and their name, probably truncated (see above). Hover your mouse over it to reveal their full name in the tooltip.

Clicking the video icon will get you a box with live preview of video stream of the selected cam. The box is an ordinary Rectangle with its Fill property set to VideoBrush, pointing to the selected video device capture source.

Only one VideoBrush can consume a single capture source, but several visual elements can share the VideoBrush. Click on the same video icon again to get another icon with the same video feed.

If you’ve got more than one, you can click on additional video icons to get video feeds from your other cams.

Oh, and running inside browser, you’ll see a nice security dialog, asking you to confirm you’re ok with that cam go live.

MouseWheel support

With video box out on the canvas, hover your mouse over it and play with your mouse wheel – the box will shrink and expand. This is achieved through the MouseWheel event, which many of the Silverlight 4 controls have. Some of them already have their own implementation of the event, generally they don’t.

In this case, a created a MouseWheelBehavior that can be applied to an element to make it work (on a Canvas). You would probably have to adapt it to use it properly; for the sake of this app, it works ok.

The interesting thing here is that if you have a multi-touch monitor, you can try a pinch zoom gesture on the box and it should shrink/expand as well => nice to see Windows APIs being used in Silverlight.

By the way, in this demo, you can drag’n’drop items on the canvas around…

WebBrowser and WebBrowserBrush

WebBrowser in Silverlight is funny… Running the app inside browser and clicking the WB icon will get you a simple box with the “HTML is enabled only in Out-of-Browser mode.” text inside. Run the app outside the browser (installed) and you’ll see a ‘proper’ web page:


The links demonstrate different aspects of browser features. Note: the last link will work only when application is installed with elevated trust (set as default with the accompanying sample code).

Adding another “browser” by clicking on the WB icon for the second time will actually bring up a rectangle, filled with the WebBrowserBrush. WebBrowserBrush mimics the referenced WebBrowser appearance at the time it was called on. Because it’s a snapshot it doesn’t react on WebBrowser changes, but you can update it the WebBrowser’s current state by calling the Redraw () method on it.

Right Mouse Click

UIElements in Silverlight 4 support right button clicks in applications, which can be conveniently used to implement a context menu. In fact, Silverlight Toolkit has an implementation of this already ready to use. This application shows how simple it is to implement. Right-click on any of the added elements to change its shape.

RichTextBox Control

A few fresh controls were introduced with Silverlight 4, RichTextBox is one of them. The app shows the simplest demo of it.


When clicking a RTB (RichTextBox) icon, a notification window will be displayed on the bottom right corner – another new control. Works outside of the browser only.

Silverlight app as a drop target

Go to your pictures folder and drag some pictures onto the app canvas – they will be shown inside the application – shows integration with the “outside world” / your app can accept files drag’n’dropped into it.


Copy text or Xaml and paste it into the app – a text element or a drawing will appear on the canvas. I usually demo this with the Expression Design – draw a shape, choose some colors for stroke and fill, than copy its Xaml (select the shape, then press Ctrl+Shit+C / Copy XAML) and paste into the app. The Xaml will deserialize into a nice Silverlight shape.

Data binding enhancements

Silverlight 4 also extends the data binding with some new properties. In sample code, you’ll notice a couple of running time labels displayed in the bottom right corner of the screen – those will display how the new properties work: the StringFormat property will let you specify the string format right there in Xaml, the TargetNullValue property value will be displayed when the source property value is null, and the FallBackValue will be displayed when there’s an error with the binding itself.


Buttons in Silverlight 4 can be assigned objects, implementing an ICommand interface, allowing for implementing separation pattern, well known from Silverlight’s older brother WPF. There are a few commands you’ll find in the sample project – FullScreenCommand, PrintCommand and DelegateCommand, the latter being mostly known for its use in MVVM pattern implementations.

Full Screen pinning

One of the best new Silverlight 4 features is definitely the ability to ‘pin’ the application to a non-primary monitor, which is especially handy for video players. To enable it, you just have to set the FullScreenOptions:

Application.Current.Host.Content.FullScreenOptions = isFullScreenWhenUnfocused ? FullScreenOptions.StaysFullScreenWhenUnfocused : FullScreenOptions.None;

Check the FullScreenCommand in source code for the implementation.


Basic printing was introduced with Silverlight 4 – you can construct individual printing pages and send them to the printer as bitmaps – enough for simple(r) scenarios, but much better things are on their way in Silverlight 5. PrintCommand shows the simplest possible implementation for printing a page visual.


There are some other Silverlight 4 features you’ll find in the sample code and I won’t be discussing here. Like MEF (Managed Extensibility Framework) or COM interop. And .NET RIA Services, but I don’t know how well they’ll play since the project is dependent on an older version.

Feel free to explore the source code. Just note – it’s demo code so don’t expect much on a best practices side…

My Month with Windows Phone 7

I had a pleasure of using a Windows Phone 7 device (LG Optimus 7 to be exact) for the past month and this is me sharing my experience with it. A quick note on my phone background: I’ve been using an iPhone for the past two years and am used to my wife’s HTC Hero (Android).

The thing is – I had to switch back to the iPhone after I returned my WP7 today (had it on a one month test drive) and it felt - weird. Let me just say that switching from the iPhone to WP7 and back felt a lot like switching from ZX Spectrum to a PC and back to the ZX (a 20-year old metaphor but who cares Smile). Something along the way of comparing serious, monochrome OS to a colorful, toyish one, if you will… Which OS suits you better remains a matter of personal taste, but to answer the question I got on one of my recent WP7 developer talks, I definitely don’t think that younger population won’t be attracted to Windows Phone 7; there are a lot of features that young audience will very much appreciate.

First, there’s the people hub – to track and manage everything and everybody from a single place is just awesome. Android is offering a similar story, but IMHO it’s not that well executed as it’s on WP7. My only wish here is that Microsoft would allow for 3rd party apps to easily integrate into the hub. And on the subject, twitter not being integrated into the hub is a huge miss, for example.

I also definitely love the Metro UI – simple, quickly recognizable graphics and large fonts. Easy for brains to process while on the move. There are, a couple of quirks I ran into… you can only add tiles on the single main screen (vertically, from the top down), and the main screen can hold up to 8 tiles. Imagine a live tile you put in the 7th row of the main screen. The gesture for unlocking the phone would be flick up, flick up. Except when you flick up the second time you can’t be sure where you’ll land - it depends on how hard you flicked. When in a hurry or on the go, that tile hunting game can be pretty time-consuming. And this is the phone that is supposed to save us from our phones, right? Either making flick up / down gestures to move a whole page up or down, or the ability to put tiles on the secondary screen on the left of the main screen would make more sense because your flick up, flick right gesture would land you exactly where you expected.
One additional thing that annoyed me was having to do two gestures to answer the call (unlock, answer) – why, oh why? Phone calls are the reason they are called phones – they should require the least amount of thinking and physical activities with this devices.
And, and I don’t know if this is related to WP7 OS or physical device - when answering a call, there was a certain lag involved before the microphone got switched on. That resulted in many confusing calls when I answered with ‘hello’, which the person on the other side didn’t hear, and waited for me to say something.

Build quality – I don’t know, the phone felt plasticky to me. I was especially worried I would accidentally pull out the Start button because of it’s embossed logo on it. And just to be clear – putting USB port on the side? That’s the worst place to put it. Cradle, anyone? Also, the photo button would be one of the greatest features on the phone if I wasn’t accidentally repeatedly hitting it when holding the phone in my left hand. It responds immediately, making your phone ready to take a photo in a matter of a second. But because of its position, it’s either a blessing, or a curse.

Ringtones – well, I tried to find a ring tone on my Optimus 7 but I couldn’t find one. The wide variety of beepy and clicky tones didn’t do much for me; I need noise to tell me it’s my phone ringing. Old phone, please!

Applications – tried them a few and they worked great… except for some with long(er), virtualized lists… jerky as hell. Hardly usable. Hard to keep up reading a list when every second or so you completely lose your track. Marketplace hung a couple of times. People’s hub crashed a couple of times, esp. when deleting a contact, imported from the SIM card. I was really impressed with the shipped IE browser. Very responsive and smooth. The whole being online experience is totally abstracted away from the phone, it feels really great.

A couple of other quirks: When trying to make a phone call, the contact info always tended to show in a landscape mode. I realized that I needed to hold my phone in a straight vertical position in order to be displayed correctly. The typing keyboard didn’t exactly liked my fingers’ typing, I was missing the keys constantly – wish there was a way to calibrate the keyboard.

In conclusion: yes, the OS has issues, some of them quite serious. From a casual user’s standpoint, I’d say the most annoying is the one with microphone lag and I hope this  will get fixed somehow, either by Microsoft or the device manufacturers. On the positive side, the phone is very easy to use and offers a great experience.
I have to say I got pretty used to it in the past month and I’m definitely considering buying my own WP7 in the near future. If I was living in a country, supported by the WP7 marketplace and the App hub, that would be a non-brainer.

Slides: Application Development for Windows Phone 7

I had the pleasure of participating in the local Microsoft roadshow that was going on in the past month.

4 talks. 4 cities. 1 subject: Application Development for Windows Phone 7.

I said I’d publish the slides. Here.

Also, from last I’ve heard, the situation for WP7 developers in Slovenia is improving. More details soon.

(Kind of) transparent Lock Screen for Windows Phone 7

Well, I thought it would be neat to have a transparent screen on my WP7 phone so I went and created a fully transparent 480x800 image and saved it as a PNG. Of course Zune software didn’t allow me to sync it with the phone (doesn’t support PNGs) so I renamed the image to JPG, which synced perfectly (shown as black image in the photo list).

I set the image as my lock screen image.

I now have a black lock screen on my phone, but whenever I touch the screen, the black fades away and reveals what’s beneath the lock screen (that’s when the lock screen is supposed to slide up a bit to hint the gesture to unlock).

Furthermore, it appears that this tap that hints the gesture also causes the reactivation of the app that was running (and deactivated) when the phone got locked. You can play a little game too… if you tap your finger fast enough to not let the lock screen fully reappear again, you can cause the app to fully reactivate (and continue to run)! I’ve got plenty of practice with this from my ZX Spectrum days so I managed to fully reactivate the official twitter app to load and refresh my timeline :) So what’s going on is the device is launching (and obviously terminating) the deactivated app each time you touch the lock screen?

I also noticed that sometimes the application bar from the deactivated app is displayed on my “transparent” locked screen even without touching it… I couldn’t figure out when this happens though.

Anyway, I’m enclosing my test transparent image here in case you’d want to give it a try.