A couple of days ago I was spreading the WPF goodness and was talking about how MVVM (Model-View-ViewModel) helps promote separation of concerns by removing the need for the code-behind file from the associated XAML file. After my statement someone replied with the following question, “So why even have it there, can you just delete it?”. Obviously I replied yes, you absolutely can delete the code-behind file from a XAML file and the application will still work. Then they replied, “That’s cool I guess, but what about the code that needs to execute, such as event handlers?”. Naturally I brought up the fact that using MVVM you don’t use event handlers, but as most developers do, they said, “Well what if I really needed it?”. My reply to that question was, “If you really had to, it is possible to write inline code inside the XAML file”.
They looked at me in amazement, “Really?”. Apparently that is a little known fact about WPF. Yes, it is absolutely possible to write inline code inside a XAML page without the need for a code-behind file, and everything will work as expected. I quickly realized that his was going somewhere I didn’t want it to go. I knew what was coming next; they asked me to show them how to do it. Uggg…
Okay here is the deal; what I am about to show you is not recommended. It goes against everything I have been teaching in the community, but if you are curious how to actually do this, it is quit simple.
As you can see the code snippet above is pretty simple. You will notice that the Button has a EventHandler defined called “btnExitApp_Clicked”. Since there is no code-behind (I deleted it) you may be expecting a compile error that says it cannot find the definition for the EventHandler. But wait, we do have the event handler defined within the <x:Code>….</x:Code> tags.
The <x:Code>….</x:Code> is a directive element defined in XAML. An x:Code directive element can contain inline programming code. The code that is defined inline can interact with the XAML on the same page. Notice that the code is inside the x:Code element and that the code must be surrounded by <CDATA[…]]> to escape the contents for XML, so that a XAML processor (interpreting either the XAML schema or the WPF schema) will not try to interpret the contents literally as XML.
That is all there really is to it. There are some limitations to using inline code, for more information you can check out the MSDN documentation. Now, I don’t want to see this in any production code.