How to supress the Alt-Key in Silverlight’s TextBox

You can restrict the input-values in Silverlight’s TextBox by handling the KeyDown-Event. But the KeyDown-Event isn’t fired if the user enters a key by pressing e.g. ALT + 123. Corresponding to the problem mentioned in, I’ll show here a short workaround by using the TextChanged and KeyUp-Event of the TextBox. Just use the following snippet, that removes a character that was added by pressing the ALT- and another Key or Key-Combination:
private void TextBox_TextChanged(object sender, TextCh… e)
  if (_altWasPressed)
    // remove the added character
    var textBox = ((TextBox)sender);
    var caretPos = textBox.SelectionStart;
    var text = textBox.Text;
    var textStart = text.Substring(0, caretPos - 1);
    var textEnd = "";
    if (caretPos < text.Length)
      textEnd = text.Substring(caretPos, text.Length-caretPos);
    textBox.Text = textStart + textEnd;
    textBox.SelectionStart = caretPos - 1;

    _altWasPressed = false;
private bool _altWasPressed;
private void TextBox_KeyUp(object sender, KeyEventArgs e)
  _altWasPressed = e.Key == Key.Alt;

Silverlight 4 – the first Beta is here

… my expectations about a Major 4.0 release next year may come true: Silverlight 4.0, WPF 4.0, .NET 4.0, Expression Blend 4.0 etc. Today Microsoft announced Silverlight 4.0 Beta 1 available for download. There are impressing features for business applications like print support, clipboard, Drag’n’Drop or local fileaccess through full trusted Silverlight-Applications. I’m glad the Galileo-Computing team and I decided to publish my upcoming Silverlight-book to version 4.0. More infos about the book soon here: Find all interesting links about the Beta 1 of Silverlight 4.0 on the site below: Cheers Thomas

Hey Thomas, what’s coming up next?

I’ll give you just a short information of what is coming up next and what I did the last months. Let’s start with the things coming up…

… what’s coming up next:

  • WebTech-Conference – 16th November, Karlsruhe/Germany Another talk about datadriven Silverlight-Applications. Meet me at this conference for discussions about WPF, Silverlight, .NET in general, my books and other topics. Find more about the WebTech-conference on webtech
  • Update of the WPF-book to .NET 4.0 and Visual Studio 2010 The WPF-book was written about .NET 3.5. Next year .NET 4.0 will be released. There are many new things introduced in WPF. The DataGrid- and DatePicker-Control, VisualStateManager, Animation Easing Functions, Layout Rounding and so on. I’m working on an update of the book that will be released next year shortly after the German Visual Studio Release.
  • Writing a german book about Silverlight 4 Currently I’m working hard on my book about Silverlight 4. I've already written about 300 pages. The book will be released next year shortly after the Silverlight 4 release. There are no comments on the Silverlight 4 release, but at PDC in mid-November there’s a session about the Silverlight-Roadmap. Then we’ll know more. So stay tuned. Find more about the upcoming Silverlight-Book on the new silverlight-category on my homepage

… what I did the last months:

  • Silverlight-Articles I’ve written six articles about Silverlight for the German dotnet-magazine. Download the articles beside others on
  • PrioConference – 28th October, Munich/Germany I had a session about datadriven Silverlight-Applications. Find the Details on the new talks-category on my homepage.
So stay tuned. If you’ve any questions, leave a comment or write me an email via the contact-form on my homepage. Thomas

PrioConference – Slides and Live-Demos & More

Thanks to all who visited my Session about building datadriven Business-Applications with Silverlight 3 yesterday at the PrioConference in Munich. I hope you enjoyed it. You can download the Slides here. To get the Live-Demos, please contact me directly via the contact-Form of my homepage and I’ll send them to you. Yesterday in the evening there was a coding-dojo about the KataPotter-Problem. If you attended the next lines of this post may be interesting for you. With the knowledge of the 2,2,2,1,1-Problem I solved the problem from “zero to hero” today while sitting in the train from Munich to Basel in about 45 Minutes. Really 45 Minutes, even a bit less. The idea to solve the problem has already been in my mind yesterday. Because of that  I couldn’t hardly believe Ralf “Dr. Clean Code” Westphal when he and his colleague Stefan said it would need 4 hours to implement the algorithm. Maybe four hours for santaclaus, but not for me. ;-) I think they exaggerated a little bit with the four hours, because it was already half past ten and everybody was thirsty... Download my 45-Minutes-not-Refactored-Algorithm (sorry for the method with more than ten lines ;-)) here. What about your algorithms? How did you solve the problem? Are there more tests for my Application that won’t work like the customer would expect? Any comments and hints are welcome. So, finally, another PrioConference is over. I enjoyed it, it was a really great event. Thanks to Dagmar, Ralph, Tilman, dotnetpro & Co. and all people behind the scences for the great organization and professionality.

Here it is: The UpdateSourceTrigger for PropertyChanged in Silverlight

Today I'll show you how to implement a PropertyChanged-UpdateSourceTrigger for Silverlight. In Silverlight a Data Binding can have different UpdateSourceTriggers. An UpdateSourceTrigger specifies, when a TwoWay-DataBinding will update its source with the value of the Target-Property.

In most cases you have a TwoWay-DataBinding on TextBoxes. When the user types something into a TextBox, it should be written back to the underlying Data-Object. The other way, when the underlying Data-Object changes, the TextBox should show the actual value of the bound property.

In this post I'll focus on the moment of writing the data back to the underlying object. In other words, when the data is updated with the text the user has typed in.

In Silverlight the underlying object is updated after the TextBox has lost its focus. In WPF, the UpdateSourceTrigger-Enum has a Member PropertyChanged. If you set the UpdateSourceTrigger-Property of the Data Binding to that value, the underlying object will be updated everytime the user changes the text. Unfortunately Silverlight doesn't contain the PropertyChanged-Value in its UpdateSourceTrigger-Enum. It only contains a Default- and a LostFocus-Member. As the name implies, LostFocus will update the source when the TextBox loses its focus. But an Attached Property would do the trick.

When I tried to solve this problem I came across a post of Michael Sync, who showed up a solution with an attached-Property that works by stealing the focus everytime the Text of a TextBox changes, and immediately set it back to the TextBox again. Find his post under

As I got deep knowledge about WPFs Binding-Engine, I could produce a solution for Silverlight, and I think I got a similar solution to Michael's, but my solution is built closer on the binding-engine and doesn't need a focus-trick. So, some details: Behind each Binding, a BindingExpression does the real work. All you have to do when the Text of the TextBox changes is to get the BindingExpression of the Data Binding and to call its UpdateSource-Method. So my Attached-Property-Class looks like the one below (Feel free to use the source in your projects, but please keep the reference to As it is, it just works for the Text-Property of TextBoxes.

/// <summary>
/// Supports a PropertyChanged-Trigger for DataBindings 
/// in Silverlight. Works just for TextBoxes
/// (C) Thomas Claudius Huber 2009
/// </summary>
public class BindingHelper
  public static bool GetUpdateSourceOnChange
    (DependencyObject obj)
    return (bool)obj.GetValue(UpdateSourceOnChangeProperty);

  public static void SetUpdateSourceOnChange
    (DependencyObject obj, bool value)
    obj.SetValue(UpdateSourceOnChangeProperty, value);

  // Using a DependencyProperty as the backing store for ...
  public static readonly DependencyProperty 
    UpdateSourceOnChangeProperty =
      new PropertyMetadata(false, OnPropertyChanged));

  private static void OnPropertyChanged
    (DependencyObject obj,
    DependencyPropertyChangedEventArgs e)
    var txt = obj as TextBox;
    if (txt == null)
      txt.TextChanged += OnTextChanged;
      txt.TextChanged -= OnTextChanged;
  static void OnTextChanged(object sender,
    TextChangedEventArgs e)
    var txt = sender as TextBox; 
    var be = txt.GetBindingExpression(TextBox.TextProperty);
    if (be != null)

The usage of the BindingHelper-class is very simple. Just add it to your project, insert a matching xmlns to your XAML file that contains the CLR-Namespace the BindingHelper-class is in. When that is done, you can simply set the UpdateSourceOnChange-Property on a TextBox to true, and if the Text-Property is databound, you'll have a Data Binding that will update its source on every PropertyChange. Like in WPF. :-)

<UserControl ...
  <Grid x:Name="LayoutRoot">
    <TextBox Text="{Binding FirstName, Mode=TwoWay}" 
    local:BindingHelper.UpdateSourceOnChange="True" />

If this post helped you, please kick it. :-) kick it on

Silverlight 3 and Expression Blend 3 are now avaibable

So I know, I've been really quiet for some time. There are many things going one. Currently I'm writing some articles (at least 6) for the German dotnet-magazine. Also I'm writing on a new book to Silverlight 3, and the timeline is very strict. That's the reason why there is not as much time for blogging, but I'll do better in the future. :-) So, Silverlight 3 and Expression Blend 3 are just out, and this time I try to be faster than Tobias, the  (even if he showed me the fastest way how to find the downloads). So find the downloads here: Expression Blend 3 with Sketchflow Silverlight 3 Software Development Kit (SDK) Silverlight 3 Tools for Visual Studio 2008 SP 1 Cheers thomas: PS: And next week I'll show you how to support a PropertyChanged-UpdateSourceTrigger for Data Bindings in TextBoxes in Silverlight

First video to Silverlight 3 appeared on Channel 9

On Channel 9 Brad Adams and Robert Hess are talking about the third Version of Silverlight. In more detail they are talking about "Silverlight 3.0 for Great Business Apps". So as the title let's except, there are features in the next Silverlight version that make it easier to build business applications. There are different things mentioned in the video, but "the super secret stuff" will be told at MIX09 in Las Vegas next week (starting at the 18th of March). So the most interessting points from the video are:
  • New set of controls ("tons of new controls")
  • Support for Back/Forward-Buttons of the Browser
  • Validation support
  • ...
There is nothing said about commands (even if some logic for commands can be used from Prism2), nothing about Triggers, nothing about CollectionViews etc. All these points would be great for Business Applications that target the Model-View-ViewModel-Pattern. So let's wait what the MIX09-conference will bring. Today there is neither a Beta nor a Customer-Technology-Preview of Silverlight 3, but community voices expect a Beta or CTP to be released after MIX09 this month. I'm looking forward to grab it.

Just converted my PHP / CSS-based Homepage to a Silverlight 2.0 Website

Three weeks ago on a saturday morning I spent my thoughts on what to do with this last free saturday before the football-season starts. Unfortunately my girlfriend was not here, so Tabletennis was no alternative. But there were other possibilities:

  • Play Guitar all day long
  • Play on my new Tenorhorn (I haven't told you that, right?)
  • Put my snowboard under my feet and go up on the mountain
  • Do some muscle-training and try to push up the 105kg more than 12 times
  • Look that Bankjob-DVD
  • ...

... while I was thinking about all that, I surved on and then I thought, why not just build my classic homepage ( totally with silverlight 2.0. And that's what I've done on that morning. :) Yesterday I've finished the page by implementing a php-call from Silverlight to make the contact-formular work (I've no ASP.Net-Support on my Webserver) Take a look at the resulting Silverlight-page on

I wanted the result to be as close as possible to the original page, and I think it is. Just with some animations. :-)

It was a rapid development process, but keep in mind that it's also a really simple site. The language switch the php/css site has I left off in the Silverlight-Version, because I went also snowboarding in the afternoon as the snow-height is 63cm on the Belchen, a mountain in the black forest not far away from my home. Instead of the language-switch I've created a "fullscreen"-button (It was a one-liner :-)). I also didn't make a real Dataaccess through WebService-calls. The text-parts are statically inside the XAML-documents. But that wouldn't be a big thing to change.

Through the development process of the Silverlight-page there were different things I knew from WPF and I was missing really extremly in Silverlight. Other things didn't work as good as I thought they should. And at least there were also some good things. Let's take a look at those that are "not so good":

The First "not-so-good": The TextBlock-Element can contain Inline-Elements. In WPF, there are many such Inline-Elements to format the text inside, like Bold, Italic, Run, LineBreak, Hyperlink, Span and so on. In Silverlight there are only two, LineBreak and Run. The one you will be missing most in Silverlight, as you are developing web-applications, is the Hyperlink-Inline. In WPF it allows you to create a hyperlink anywhere in the Text. As Silverlight doesn't have this one, you can't create a hyperlink inside your text out of the box. Silverlight has a HyperlinkButton, but that can't be put inside a TextBlock. So what's the solution? I've used a WrapPanel in combination with multiple TextBlocks and Hyperlinks so that it looks like the Hyperlinks are inside the Text. But in fact they aren't, it just looks so. There are also ThirdParty-Controls available allowing you to write text that contains hyperlinks. I hope the Hyperlink-Inline will be available in Silverlight 3.0

The Second "not-so-good": The TextBlock-Element can't justify the text it contains.

The Third "not-so-good": The Image-Element only supports jpeg and png-files. As the images in the "articles"-Section of my homepage were gif-files, I needed to convert them. Maybe in a future release of Silverlight the Image-Element supports more types. But this point isn't really bad, it's not a big thing to convert images.

The Fourth "not-so-good": If you set the silverlight plugin's params windowsless to true and background to transparent, you can display a custom html-background. I tried that and set the silverlight-plugin to a width of 800. If you use such a html-background, your silverlight-content will flicker when you animate it. That's because the plugin is in an overlay over the website. That wouldn't change in future versions. So the golden rule is not to use animations if the plugin's background is transparent and the plugin is windowless. Or another option is to set the plugins width and height to 100% so that you don't see any other html-contents. The latter I've done.

The last "not-so-good": The Enum-class has no GetNames-Method. To loop through an enum, you'll need reflection. I've done it this way, where Category is my enum:

foreach (FieldInfo fi in typeof(Category).GetFields(
  BindingFlags.Static | BindingFlags.Public))
  Category category = 
    (Category)Enum.Parse(typeof(Category), fi.Name, true);

Ok, that's all. There are also more points, e.g. Silverlight doesn't support Triggers and Commands out of the box. But I'll only mention those points that have been important when converting my website to Silverlight 2.

Now let's take a look at the great things. I'll just mention three:

The First "great one": You can use C# and common .NET classes you are already familar with. This aspect is really a big one, even if it was said already so much.

The Second "great one": With Expression Blend and Visual Studio, Animations and UI-Design can be done very fast. If you've some experience with WPF-Userinterfaces, you'll do it in Silverlight the same way.

The Last "great one": As my Homepage contains a contact-formular, I needed some service to call to send an email from that formular in Silverlight. Unforetunately my webserver doesn't understand .asmx or .svc. So I tried to call a php-script from Silverlight for sending the email. And hey, it wasn't difficult at all. The WebClient-class in Silverlight has everything you need to make a call on a lower level to anything in the web.

So stay tuned and take a look at the Site on