Archive for the ‘WPF’ Category

Don’t Write WPF Converters; Write C# Inline In Your XAML Instead Using QuickConverter

December 13th, 2013 12 comments

If you’ve used binding at all in WPF then you more then likely have also written a converter.  There are lots of tutorials on creating converters, so I’m not going to discuss that in length here.  Instead I want to spread the word about a little known gem called QuickConverter.  QuickConverter is awesome because it allows you to write C# code directly in your XAML; this means no need for creating an explicit converter class.  And it’s available on NuGet so it’s a snap to get it into your project.


A simple inverse boolean converter example

As a simple example, let’s do an inverse boolean converter; something that is so basic I’m surprised that it is still not included out of the box with Visual Studio (and why packages like WPF Converters exist).  So basically if the property we are binding to is true, we want it to return false, and if it’s false, we want it to return true.

The traditional approach

This post shows the code for how you would traditionally accomplish this.  Basically you:

1) add a new file to your project to hold your new converter class,

2) have the class implement IValueConverter,

3) add the class as a resource in your xaml file, and then finally

4) use it in the Converter property of the xaml control.  Man, that is a lot of work to flip a bit!

Just for reference, this is what step 4 might look like in the xaml:

<CheckBox IsEnabled="{Binding Path=ViewModel.SomeBooleanProperty, Converter={StaticResource InverseBooleanConverter}" />


Using QuickConverter

This is what you would do using QuickConverter:

<CheckBox IsEnabled="{qc:Binding '!$P', P={Binding Path=ViewModel.SomeBooleanProperty}}" />

That it! 1 step! How freaking cool is that!  Basically we bind our SomeBooleanProperty to the variable $P, and then write our C# expressions against $P, all in xaml! This also allows us to skip steps 1, 2, and 3 of the traditional approach, allowing you to get more done.


More examples using QuickConverter

The QuickConverter documentation page shows many more examples, such as a Visibility converter:

Visibility="{qc:Binding '$P ? Visibility.Visible : Visibility.Collapsed', P={Binding ShowElement}}"


Doing a null check:

IsEnabled="{qc:Binding '$P != null', P={Binding Path=SomeProperty}"


Checking a class instance’s property values:

IsEnabled="{qc:Binding '$P.IsValid || $P.ForceAlways', P={Binding Path=SomeClassInstance}"


Doing two-way binding:

Height="{qc:Binding '$P * 10', ConvertBack='$value * 0.1', P={Binding TestWidth, Mode=TwoWay}}"


Doing Multi-binding:

Angle="{qc:MultiBinding 'Math.Atan2($P0, $P1) * 180 / 3.14159', P0={Binding ActualHeight, ElementName=rootElement}, P1={Binding ActualWidth, ElementName=rootElement}}"


Declaring and using local variables in your converter expression:

IsEnabled="{qc:Binding '(Loc = $P.Value, A = $P.Show) => $Loc != null &amp;&amp; $A', P={Binding Obj}}"

* Note that the "&&" operator must be written as "&amp;&amp;" in XML.


And there is even limited support for using lambdas, which allows LINQ to be used:

ItemsSource="{qc:Binding '$P.Where(( (int)i ) => (bool)($i % 2 == 0))', P={Binding Source}}"


Quick Converter Setup

As mentioned above, Quick Converter is available via NuGet.  Once you have it installed in your project, there are 2 things you need to do:

1. Register assemblies for the types that you plan to use in your quick converters

For example, if you want to use the Visibility converter shown above, you need to register the System.Windows assembly, since that is where the System.Windows.Visibility enum being referenced lives.  You can register the System.Windows assembly with QuickConverter using this line:


In order to avoid a XamlParseException at run-time, this line needs to be executed before the quick converter executes.  To make this easy, I just register all of the assemblies with QuickConverter in my application’s constructor.  That way I know they have been registered before any quick converter expressions are evaluated.

So my App.xaml.cs file contains this:

public partial class App : Application
	public App() : base()
		// Setup Quick Converter.

Here I also registered the System assembly (using “typeof(object)”) in order to make the primitive types (like bool) available.


2. Add the QuickConverter namespace to your Xaml files

As with all controls in xaml, before you can use a you a control you must create a reference to the namespace that the control is in.  So to be able to access and use QuickConverter in your xaml file, you must include it’s namespace, which can be done using:



So should I go delete all my existing converters?

As crazy awesome as QuickConverter is, it’s not a complete replacement for converters.  Here are a few scenarios where you would likely want to stick with traditional converters:

1. You need some very complex logic that is simply easier to write using a traditional converter.  For example, we have some converters that access our application cache and lock resources and do a lot of other logic, where it would be tough (impossible?) to write all of that logic inline with QuickConverter.  Also, by writing it using the traditional approach you get things like VS intellisense and compile-time error checking.

2. If the converter logic that you are writing is very complex, you may want it enclosed in a converter class to make it more easily reusable; this allows for a single reusable object and avoids copy-pasting complex logic all over the place.  Perhaps the first time you write it you might do it as a QuickConverter, but if you find yourself copy-pasting that complex logic a lot, move it into a traditional converter.

3. If you need to debug your converter, that can’t be done with QuickConverter (yet?).



So QuickConverter is super useful and can help speed up development time by allowing most, if not all, of your converters to be written inline.  In my experience 95% of converters are doing very simple things (null checks, to strings, adapting one value type to another, etc.), which are easy to implement inline.  This means fewer files and classes cluttering up your projects.  If you need to do complex logic or debug your converters though, then you may want to use traditional converters for those few cases.

So, writing C# inline in your xaml; how cool is that!  I can’t believe Microsoft didn’t think of and implement this.  One of the hardest things to believe is that Johannes Moersch came up with this idea and implemented it while on a co-op work term in my office!  A CO-OP STUDENT WROTE QUICKCONVERTER!  Obviously Johannes is a very smart guy, and he’s no longer a co-op student; he’ll be finishing up his bachelor’s degree in the coming months.

I hope you find QuickConverter as helpful as I have, and if you have any suggestions for improvements, be sure to leave Johannes a comment on the CodePlex page.

Happy coding!

Categories: C#, WPF, XAML Tags: , , , , , , ,

Adding ValueChanged events to Dependency Objects in WPF

April 17th, 2011 No comments

You may be wondering which is the best way to hookup a DependencyProperty’s Callback event handler to handle Value Changed events.  The two methods to consider are:

Method 1 – Use static event hanlders, like so:

public virtual int SelectedID
	get { return (int)GetValue(SelectedIDProperty); }
	set { SetValue(SelectedIDProperty, value); }

public static readonly DependencyProperty SelectedIDProperty =
	DependencyProperty.Register("SelectedID", typeof(int), typeof(SelectorBase), 
                new PropertyMetadata(0, new PropertyChangedCallback(OnSelectedIDChanged)));

private static void OnSelectedIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	// Perform event handler logic


Method 2 – Hookup event handler at initialize, and remove it during Dispose(), like so:

// Constructor
public SelectorBase()

private void HookupEventHandlers()
	TypeDescriptor.GetProperties(this)["SelectedID"].AddValueChanged(this, SelectedID_ValueChanged);

private void RemoveEventHandlers()
	TypeDescriptor.GetProperties(this)["SelectedID"].RemoveValueChanged(this, SelectedID_ValueChanged);

protected override void Dispose(bool isDisposing)
	// If managed resources should be released
	if (isDisposing)

public virtual int SelectedID
	get { return (int)GetValue(SelectedIDProperty); }
	set { SetValue(SelectedIDProperty, value); }

public static readonly DependencyProperty SelectedIDProperty =
	DependencyProperty.Register("SelectedID", typeof(int), typeof(SelectorBase), new PropertyMetadata(0));

private void SelectedID_ValueChanged(object sender, EventArgs e)
	// Perform event handler logic

So the advantage to using method 1 is that we have access to the property’s old and new values, we don’t have to worry about memory leaks (since the event handler is static), and if we create 100 instances of the control we still only have one static event handler in memory, instead of 100 local ones.  The disadvantage to method 1 is that these event handlers are going to exist in memory for the entire lifetime of the app, even if the view/control they are on is never referenced.

The advantage to using method 2 is that the event handlers only exist in memory if the view/control they are on is actually open.  The disadvantage is that we don’t have access to the property’s old value, and the developer has to remember to properly unhook the event in order to avoid a memory leak.

So method 1 is best suited to items that are used in many places (such as custom controls that may be plastered all of the place), while method 2 is best suited for views where there is likely to never be more than a few instances open at any given time, or in places that may not be accessed at all (e.g. a settings menu that is rarely accessed).

My WPF Binding won’t work. WTF!

April 17th, 2011 No comments

At one point or another I’m sure we’ve all been confused as to why our binding won’t work.  Here’s a couple things to keep in mind:

– have you set the DataContext to be the class containing the property you are binding to?  This can be done in XAML or in the code-behind.  For example, put "this.DataContext = this" in the code-behind file’s constructor.

– is the property you’re binding to public?  Also, it must be a property (with get; set; accessors), not a field (i.e. class variable).

– if you are using two way binding, do you have both a Get and Set accessor on the propery?

– if you are trying to set bindings on a usercontrol that you are placing on your form, you may have to set the DataContext in that control, or reference the property dynamically using something like:


  CanModifyAmount="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:WpfViewBase}},

Path=CashOutViewModel.CanModifyAmount, Mode=OneWay}"

  CashDetail="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type src:WpfViewBase}},

Path=CashOutViewModel.CashOutModel.CashOut.CashDetail, Mode=OneWay}"/>

If you still don’t know why your binding isn’t working, be sure to check the Output window in Visual Studio while debugging, as it will display any binding errors that occur and (hopefully) give you more information about the problem.  You can also change the level of verbosity that is displayed for Binding errors, so if you aren’t getting enough information, in Visual Studio go into Tools -> Options -> Debugging -> Output Window and make sure Data Binding is at least set to Warning.

If changes made to the UI propogate to the code-behind, but changes made in the code-behind don’t propogate to the UI, you will either need to use the INotifyPropertyChanged pattern, or implement your code-behind properties as DependencyProperties, in order to let the UI know that the value has been updated and show the change.

Categories: Binding, WPF Tags: , , ,

Setting focus to an element in WPF

April 17th, 2011 No comments

So if you are trying to set focus to a WPF element, but are unable to.  Here is a quick checklist to go through:

– is the control you are trying to set focus to Enabled, Visible, Loaded, and Focusable.  If any of these properties are false, you cannot set focus to the element.

If you are using Binding to set these properties, make sure the binding is firing before you are trying to set the focus.

– does the control that already has focus allow focus to be taken away? If the control that currently has focus overrides the PreviewLostFocus event, it can set e.Handled to true to prevent other controls from stealing focus from it.

If all of these conditions seem to be met, but you still cannot seem to set the focus to a control, is another operation moving focus from your control to another control after you set focus to your control?  From a dispatcher perhaps?

Using the tool Snoop is great for viewing what control in your WPF application has focus, and is very useful in debugging for seeing what controls are recieving focus.  Once you know what control is getting focus instead of your control, you can put a breakpoint in the control’s GotFocus event to debug and see when focus is being moved to the control, and what fuction is performing the operation to move the focus.

Categories: WPF Tags: , , , ,