WPF Tips & Tricks

This idea of the tips & tricks is just as a scratch pad for code snippets etc. relating to the subject that don’t warrant a whole post to themselves. Here’s a few WPF tips & tricks.

StringFormat

I seem to always forget this, basically a simple way to apply string formatting to a TextBox (for example) is to use StringFormat

<TextBox Text="{Binding Fahrenheit, StringFormat={}{0:#.##}}" />

The above formats the TextBox string to 2 dp. Fahrenheit in this instance being a float.

Another example with DateTime formatting

<TextBlock Text="{Binding LastUpdateDateTime, StringFormat={}{0:HH:mm:ss dd/MM/yyyy}}" />

Setting the DataContext in XAML

Another one I seem to forget a lot. Admittedly I only tend to use it for simple apps. but still.

<Window.DataContext>
   <Thermometer:ConversionViewModel />
</Window.DataContext>

So we can set the data context on the main window easily enough using this method but there’s also a couple of other ways to create a view model in XAML…

See Settings the DataContext in XAML and the ObjectDataProvider

Order of XAML attributes

A little gotcha to watch out for. Take something like a ComboBox which has the SelectedValue and ItemsSource attributes.

Beware that if SelectedValue appears before ItemsSource you may well find the SelectedValue not set when the binding first takes place. Switch the two around so ItemSource appears first and this should fix the problem.

Detecting whether you’re in design mode

If you need to check whether your control (or general UI) is currently being displayed in design mode, i.e. maybe to not waste time displaying animation or the likes, use

if(!!DesignerProperties.GetIsInDesignMode(this))
{
   // not in design mode
}

Beware d:DesignWidth & d:DesignedHeight as opposed to Height and Width

This is a stupid tip and everyone should know but it’s funny how easy it is to miss this.

I was designing a simple little UI in WPF using both XAML code and the WPF Designer. I made a change to the Width and Height of the control. Unbeknown to me the actual control’s Width and Height were set, not the DesignWidth & DesignHeight. Hence when I placed the control onto another control I couldn’t understand initially why the control was not expanded correctly, when I resized the app.

So beware the WPF designer switching to setting your actual Width and Height as opposed to the d:DesignWidth and d:DesignHeight as it can lead to some head scratching when views are not resizing as expected.