You Can Write Inline C# in XAML – But Should You?

Did you know that you can write inline C# in your XAML file with the x:Code Intrinsic type? When I stumbled on this feature, my first reaction was, “Wow, I didn’t know you could do that!”  After several years of using WPF, I thought I knew all the tricks. Discovering something new was exciting!

The initial thrill was tempered once I thought about it, however, and I was soon saying, “Oh no, people should never use this!” I generally keep an open mind about code, because even if it doesn’t fit my immediate needs, I know someone might find it useful. With inline C#, however, I am slightly bewildered that this feature was ever considered useful enough for Microsoft to include.

What does it look like?

Here is an example program I wrote entirely in XAML and inline C#.  It does multiplication and validates that you entered numbers in the input field. You can download the entire project on GitHub.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<Window x:Class="inlinetest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        x:Name="root">
    <StackPanel HorizontalAlignment="Center">
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="0,100,0,20">
            <TextBox Text="{Binding LeftSideNumber, ElementName=root}" 
                     PreviewTextInput="ValidateIsNumber" Width="50" Margin="0,0,10,0"/>
            <TextBlock>X</TextBlock>
            <TextBox Text="{Binding RightSideNumber, ElementName=root}" 
                     PreviewTextInput="ValidateIsNumber" Width="50" Margin="10,0,10,0"/>
            <TextBlock Margin="0,0,10,0">=</TextBlock>
            <TextBlock x:Name="Answer"/>
            <x:Code>
                <![CDATA[
                    private System.Text.RegularExpressions.Regex isNumberRegex = 
                      new System.Text.RegularExpressions.Regex(@"^-*[0-9,\.]+$");
 
                    public string LeftSideNumber { get; set; }
                    public string RightSideNumber { get; set; }
 
                    void CalculateClicked(object sender, RoutedEventArgs e)
                    {
                        var left = Convert.ToDouble(LeftSideNumber);
                        var right = Convert.ToDouble(RightSideNumber);
                        Answer.Text = Convert.ToString(left * right);
                    }
 
                    void ValidateIsNumber(object sender, TextCompositionEventArgs e)
                    {
                        e.Handled = !isNumberRegex.IsMatch(e.Text);
                    }
                ]]>
            </x:Code>
        </StackPanel>
        <Button Click="CalculateClicked" Width="100">Calculate</Button>
    </StackPanel>
</Window>

Example inline XAML program

What is its purpose?

I found two articles in the MSDN documentation that discuss the x:Code type.

The second article even came with this warning:

“You should consider avoiding or limiting the use of inline code. In terms of architecture and coding philosophy, maintaining a separation between markup and code-behind keeps the designer and developer roles much more distinct.”

In today’s world of the Model View ViewModel (MVVM) pattern, where we limit our code-behind code, it’s hard to imagine a useful purpose for inline C# in XAML. The function exists, though, so someone at Microsoft believed it had a legitimate use.

Could dynamically loading XAML be a use case?

The following code snippet will dynamically load a XAML file at runtime.  Could this feature be the reason for inline C# in XAML?

1
2
var myControlFromFile = XamlReader.Load(my_xaml_file_stream) as FrameworkElement;
layoutRoot.Children.Add(myControlFromFile);

This code will add the loaded element into your application’s visual tree. Unfortunately, one limitation of loading XAML in this way is the inability to load the associated code-behind class. All events or data contexts have to be hooked up after loading the XAML file into your existing code.

Using inline C#, you could perhaps circumvent this limitation. C# is a static language, though, so this outcome would be nothing short of a miracle. In fact, the documentation for the x:Code intrinsic type states the x:Class Directive must be provided,  and the documentation for the XamlReader states it cannot contain a x:Class Directive; therefore, you can’t use the XamlReader to load a XAML file with a x:Code type. In my sample program above, I had to specify the class x:Class="inlinetest.MainWindow". All inline C# is compiled as a partial of this class. Considering multiple scenarios, I cannot reason a good use case for inline C#.

What could possibly go wrong?

Ultimately, there are many reasons to avoid inline C#:

  • No separation between the user interface and the business logic.
  • Not easily testable with unit tests.
  • No intellisense while typing.
  • You cannot set a breakpoint to debug.
  • When an exception occurs, you have no source view to see where the exception came from.
  • You have to fully quality every type.  You can’t add a using statement.
  • and many more limitations listed in the documentation.

I simply cannot recommend this feature, and I struggled with providing it any wider exposure at all. I recognize, however, that many developers may yet discover this feature, and I must caution against considering such poor design. Can you think of a good reason to use inline C#?