Conditional Formatting of a TextBox


I recently came across a scenario where I needed to bind a TextBox to a domain property but also have the value formatted for display. To make things more interesting the format was to be dynamic and the value needed to be editable.

The initial investigation led me to consider a ValueConverter. Ideally the TextBox.Text property could be bound and the Converter could be used to format to/from the required on-screen value. For a dynamic format it would be nice to bind the ConverterParameter to a property that exposed the format. Of course that doesn’t work because ConverterParameter doesn’t support data binding. I found a hack that gets around this – but it isn’t pretty. There are also some examples of using a MultiValueConverter and passing both the value to format and the format string itself as separate individual bindings. This approach has some difficulties too when converting both ways and its just feels like an abuse of the ValueConverter.

This lead me to think about the problem a little more… maybe a different approach is required? Thinking back to the WinForms days and I realised that I had solved this problem before, several times in fact. My approach to this problem for WinForms had been:

  • Subclass TextBox and add a Value property of type object that allows data binding to data types other than just string. Common types that could be used with a TextBox include int, decimal, double, bool, DateTime and enums.
  • The inherited TextBox also has a Format property. On GotFocus the Value property is formatted and used to populate the Text property. On LostFocus the reverse happens, the Text property is parsed back into the Value property. Of course this requires the data type to be known so a DataType property is required as well.

The benefits that this has:

  • TextBox works for data types other than string.
  • The value is formatted as required for display but upon data entry (GotFocus) the formatting is removed. This actually makes it easier to enter/modify the value because you don’t need to parse currency symbols, percentage signs and the like.

So the approach sounds good and its worked well for me in WinForms but its… well… not very WPF’ish. Upon starting any major development the first requirement in WinForms was to subclass all the controls – because they were just so lacking if functionality and even more importantly didn’t expose a common set of interfaces. However, I very rarely subclass controls in WPF – instead we can use attached behaviors to extend the control.

The attached behaviors required are:

  • object TypedValue
  • Type DataType 
  • string StringFormat

In XAML instead of binding to the TextBox.Text property we bind to the TypedValue attached property. The StringFormat can also be bound. The DataType can be inferred by the TypedValue – but for nullable types its best to be set explicitly. With a sample class as follows:

public class ModelItem
public object Value { get; set; }
public string Format { get; set; }

The XAML is then:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
<DataGridTextColumn Header="Any Type TextBox">
<Style TargetType="{x:Type TextBlock}">
<Setter Property="local:TextBoxExtensions.StringFormat" Value="{Binding Format}"/>
<Setter Property="local:TextBoxExtensions.TypedValue" Value="{Binding Value}"/>
<Style TargetType="{x:Type TextBox}">
<Setter Property="local:TextBoxExtensions.StringFormat" Value="{Binding Format}"/>
<Setter Property="local:TextBoxExtensions.TypedValue" Value="{Binding Value}"/>
<DataGridTextColumn Header="Format" Binding="{Binding Format}" IsReadOnly="True"/>
<DataGridTextColumn Header="Value" Binding="{Binding Value}" IsReadOnly="True"/>

Which generates a DataGrid bound to a collection of ModelItems. Each ModelItem allows a different data type and format to be applied – great for a “user-defined fields” scenario.

Populating the ModelItems collection as follows in our main ViewModel:

    public class Model
public Model()
Primary = new ModelItem() { Format = "{0:#,##0.0}", Value = 12345678.765 };
Items = new ObservableCollection<ModelItem>();
Items.Add(new ModelItem() { Format = "{0:C2}", Value = 123.42 });
Items.Add(new ModelItem() { Format = "{02}", Value= 0.125 });
Items.Add(new ModelItem() { Format = "{0}", Value = "Fred" });
Items.Add(new ModelItem() { Format = null, Value = true });
Items.Add(new ModelItem() { Format = "Uncle {0}", Value = "George" });
Items.Add(new ModelItem() { Format = null, Value = Colors.Black });
Items.Add(new ModelItem() { Format = null, Value = System.DayOfWeek.Monday });
Items.Add(new ModelItem() { Format = "{0:0;minus 0;zip}", Value = -123.4 });
public ModelItem Primary { get; set; }
public ObservableCollection<ModelItem> Items { get; private set; }

Generates the following grid, which allows for editing of the strongly typed values.


Word Puzzle to Silverlight Phone – Part 2

Finally got interaction and feedback happening on the Silverlight port of Word Puzzle. This was so much more difficult than I had imagined – feels like learning WPF from scratch. I am beginning to believe that it would be easier to approach Silverlight with no WPF knowledge whatsoever.

  • I had to cater for not having DataTriggers – and then not being able to get behaviours/triggers/states to work like I wanted. In the end I used a ValueConverter to hack the selection and solved colours – yuk!
  • Had some weird issues with the MouseMove event – had to use CaptureMouse to get position readings outside the original UI element – wasn’t a requirement for WPF.
  • Spent ages working through really minor bugs that just aren’t reported properly in Silverlight. Things as simple as referencing a resource that doesn’t exist (due to misspelling) generates a super generic error message.
  • Had to create a proper custom layout panel for the words to position and rotate the highlight boxes. This was actually an improvement on the original version.

Anyhow – now have a playable version on the emulator. Slow progress, but progress nonetheless.

WordPuzzle_Stage2  WordPuzzle_Stage2_EndGame

Desk Genie

I’ve recently had the opportunity to reduce my material possessions to no more than can be carried in eight suitcases. This was quite a liberating experience. Particularly when you take into account that those eight suitcases were for my entire family – only two contained my stuff.

One of the fun parts of going through this experience is that we get to buy some essentials. Once all the boring stuff (like furniture) is out of the way I got to concentrate on replacing a few tech items. The idea being to create an area at home from which I can work remotely whilst remaining highly productive. First on the list was a more powerful, yet highly portable laptop, and a keyboard and cheap wide screen monitor to go with it.

This gave me the essentials but there were two minor flaws in the setup.

  1. The laptop only had three USB ports (not uncommon for laptops). Obviously this isn’t going to be enough even at this early stage – keyboard, mouse, phone, external hard drive. (Luckily the printer is on the network).
  2. My aging Sony Cybershot DSC-V1 uses the standard sized (old) memory stick format which doesn’t fit in the card reader on the Z-Series laptop. This means yet another device to connect via USB.

Enter the Desk Genie the perfect accessory for my HTC Touch Diamond2. This little gadget is designed to meet three simple objectives.

  1. Act as a multi-format card reader
  2. Act as a USB hub and power charger
  3. Provide a platform on which to mount portable devices so they are easily visible when sat at a desk.

Desk Genie Unboxed  Desk Genie what you get

What’s in the box? Comes with plenty of charger connections – the only two of interest for me were the mini and micro-USB.

I’ve had this item for almost a week now, and I’ve tried it out both at work and at home. Here’s my thoughts.


  • It works well as phone holder. The “sticky” surface does exactly what it says – hold the phone firmly in place without having pesky catches, clips, Velcro etc. The viewing angle worked well for the desk and chair heights that I use both at home and work.
  • Charger worked fine for charging my HTC Touch Diamond, though had trouble with the Blackberry (see below).
  • As a USB hub it works flawlessly (as you’d hope). I’ve had my 1.5 Tb external drives connected through this and copied large volumes of data without any issues.
  • Has a very muted blue “glow” indicator to let you know its connected.


  • An extra USB outlet would have been nice.
  • The memory stick reader isn’t a perfect fit. I had to insert the memory stick on a slight angle – was a bit of a knack getting the hang of it but once you worked it out wasn’t a big deal. I’ve had the same problem with other multi-card readers (like the one in my Zalman HD160 HTPC case).
  • When connecting my Blackberry via the power charger (with the included micro-USB adapter) it didn’t work. Not sure what the problem was – maybe not enough “juice”? Connected via one of the USB ports and everything was fine – connectivity and charging.



My favourite configuration for this device was to provide both charging and connectivity for my phone by using one of the USB ports rather than using the charging cable. Whilst this does mean I lose one of the two USB ports I like having the device connected for ActiveSync and for copying across podcasts.

The number one feature of this gadget for me though is that it holds the phone at a perfect viewing angle whilst connected. I would have loved one of these at my previous work desk where I would continuously have to pick the phone up to look at whether I’d missed a phone call, email or text whilst away from my desk. If that’s what you really care about then

I’m pretty happy with this gadget – it does what it says and for me it happened to come along at a time when I needed the USB and memory card features. Now all I have to do is figure out whether I keep it on the desk at home, or the one at work?

Thanks to Natalie from who was kind enough to send me a Desk Genie to review.

Porting WPF Word Puzzle to Windows Phone Silverlight – Part 1

To date I’ve avoided doing any serious development in Silverlight. Every time I’ve tried to tackle it I get so frustrated with all the missing pieces. Besides which I’ve never had a good reason to do any Silverlight work – I’ve never been a fan of applications that run in a browser.

With the release of the Windows Phone Series development tools however, I now have a good reason. So I figured I’d pick a relative simple, small scale WPF application that actually makes some sense to run on a mobile device. Rather than starting it from scratch I just wanted to port it from WPF – so I chose the Word Puzzle program that I wrote a couple of years back. I figured it was a good choice because it met the criteria above, plus I’d already stripped it back a little to make sure it could run as an XBAP application.

Inspired by Rob’s posts on porting NProf to Silverlight I thought it may be of some interest to list off the issues that I come up against as I go through the process of porting. This first list represents me starting a new Windows Phone project and copying over classes and XAML files to get something to compile and look recognizable. The following represents about 2 hours work:


However, along the way I came across this list of issues:

  • No Viewbox
  • No MouseDown or MouseUp
  • No UniformGrid
  • No Image.StretchDirection
  • x:Type is not supported
  • No Style.Triggers
  • No DockPanel
  • No RoutedCommand
  • No KeyGesture
  • No DataType on DataTemplate?
  • No ValueConversion
  • No DefiningGeometry on Shape
  • No BooleanToVisibilityConverter
  • No DynamicResource
  • No WrapPanel

I haven’t verified the above list yet – save that they gave me compilation errors. I easily found a replacement UniformGrid, but there are a few items on the list that may pose more of a problem.

The next step is to get some level of interaction working.

My views on Windows Phone 7 Series

I have mixed feelings about Windows Phone 7 Series. Whilst the new user interface is refreshingly different I’m not overly optimistic about its effectiveness. As more information about the new OS was made available I began to get a better idea of the target audience.

My current feeling is that Windows Phone 7 Series will become a solid offering for the mass consumer market. It will throw off the shackles of the Windows Mobile legacy and become a more stable, more consistent and vastly more appealing operating system for mobile devices. The only people that are likely to be disappointed by the new OS are the few die-hards that are currently running Windows Mobile 6.5 and below. The kind of people that wouldn’t be satisfied with an iPad when there are much more powerful and efficient means at hand. Those with such outlandish views that they believe touch interfaces (capacitive or otherwise) offer some amusement but just don’t cut it for serious tasks. People that believe copy/paste and multi-tasking are key operating system features. Alas I am once such person.

I think Windows Phone 7 Series has the potential to be very successful and I certainly hope that it is. For me a lot about having a phone is having a mobile device for which I can write applications. The ability to finally use Silverlight is something that I’m really excited about. So while the operating system itself is not something that I’m all that enthusiastic about the developer experience so far looks great.

New Laptop – Sony Z Series

The last two months have been pretty hectic for me… new job, new residence, new country/continent/hemisphere.

When we moved I packed all my desktop computers (dev box, HTPC, Home Server and son’s PC) into storage. This means for the last two months I’ve been using my Fujitsu tablet PC for all my computing requirements, occasionally also resorting to my HP mini notebook.

The plan was to purchase a desktop PC when we got settled in – something powerful enough to by a good dev box and occasional gaming. However – two things quickly became apparent to me. Firstly – purchasing computer hardware in the US is not as convenient as I first imagined.

  • Online delivery times for most sites (including Dell and Sony) were measured in weeks – I want next day delivery!
  • It’s nowhere near as cheap as I had hoped – especially when you always need to add taxes
  • Laptops are cheaper to buy than desktops once you include screens, keyboards, wireless etc. Of course this point is debatable based on your requirements.

My requirements were:

  • I5 or I7 processor
  • Minimum 4Gb RAM
  • Dedicated mid-range graphics card
  • Dual monitor – with at least one 1920 x 1080 display

Nice to have:

  • 120+ Gb SSD drive
  • Wireless N

The desktops I priced that matched these requirements were priced around $1200. Too expensive! I deliberated for two weeks, trying to find cheaper alternatives – including building a machine from components (which is how I normally buy desktop PCs) and then finally gave up. Figuring I was going to have to spend that kind of money I decided to look at higher end laptops that offered equivalent power. Eventually I settled on the new Sony Z Series together with a cheap 24 inch screen.




  • Light – seriously light – much lighter than my Tablet PC – 3 lbs / 1.3kg
  • I5 processor
  • Dual graphics – dedicated when you need it then drops back automatically to use integrated for lower power use
  • Wireless N / Bluetooth
  • Reasonable battery life – 5 hours
  • SSD drive is awesome
  • Comes with a really nice set of active noise cancelling bud-style headphones
  • Keyboard looks gimmicky – but actually works really well, has a really solid feel, possibly the best laptop keyboard I’ve used. This was really quite a surprise.
  • Ambient light detector used to automatically set screen brightness (and optionally backlights keyboard) – works really well in our dimly lit apartment or when working near a window during the day.
  • HDMI connection to 1920 x 1080 monitor – including sound (though the monitor I bought has ridiculously terrible speakers).


  • Doesn’t read original memory sticks – it has a MagicGate slot – presumable only takes the Duo format?
  • Its expensive when you can get a lot of reasonable laptops for around half the price.