WPF: XAML Attribute Order Matters

I think the most annoying thing about WPF is that for any given task everything goes fine, for a few hours, then you do something and you’re stumped why it’s not working. One such issue I hit recently is that some properties have built-in dependency on other properties but since there’s no way to express such a dependency if the control doesn’t correctly handle out-of-order processing of the attributes, order becomes important and is easy to overlook.

For example, you might write something like this for your buttons command binding to the corresponding view model:

* <Button Command="{Binding Path=GoCommand}"<br></br>
CommandParameter="{Binding Path=Thing}">Go!</Button>

*

Now, for most people that’s not actually a problem. Because if in the process of creating the control focus is shifted to the window that contains it, you’ll fire enough checks that the command will be evaluated multiple times and the button will become enabled. But if you’re creating the control on another window or control that doesn’t contain the focus, the order of the above code will result in a disabled button (assuming that your command requires having a non-null parameter) until you shift focus.

To correct this problem, it’s really simple, but not immediately obvious because order of attributes in XAML isn’t something you’d normally think was important. If you just swap the attributes so that you bind the CommandParameter first, then the Command will have the correct parameter when it gets evaluated.

* <Button CommandParameter="{Binding Path=Thing}"<br></br>
Command="{Binding Path=GoCommand}">Go!</Button>

*