Search code examples
xamluwpdrytemplate-enginereusability

Is there an easy way to include chunks of xaml code?


When coding xaml we have wonderful resource dictionaries, styles, user controls, and templated controls to make xaml extensible and easy to reuse.

But what about including the same chunck of xaml code multiple places?

Let me give an examle.

I have a grid definition I want to use on all my xaml pages.

<!--Row definitions-->
<Grid.RowDefinitions>
    <RowDefinition Height="50" />
    <RowDefinition Height="Auto" />
    <RowDefinition />
</Grid.RowDefinitions>

As things are now, I simply copy paste this definition on all my xaml pages. As you can imagine, adding even the simplest of changes to the grid definition becomes a nightmare. It's anything but DRY code.

So, is there a smarter alternative? Like defining the block in a seperate xaml file, and then write something like

<includes:GridDefinitions>

In PHP you can get template tools like Twig and Blade, where you write a master template, and then extend it (Example below is from twig)

base.html.twig

{% block content %}

{% endblock %}

page.html.twig*

{% extends "base.html" %}

{% block content %}
    Content of the page...
{% endblock %}

They even have an include statement, which simply takes all the content of one html file and includes it wherever you put the tag

{{ include('page.html') }}

So here comes the question

Does xaml have some sort of template engine or include function that I don't know of yet? Or is there a way to use resource dictionaries etc, to achieve a similiar DRY code effect?

If what I'm looking for is unclear, feel free to post a comment and ask for more information.


Solution

  • From my experience there is not direct answer to your question, but here are some options you can consider:

    1. For parts of UI, stiles,... -- define UserControls, dictionaries, ContentConrols... in separate files as you mention in first line. (Just in case, if you want to "stylize" things like RowDefinitions you should wrap them into Dependency Objects - here is a detailed article.)
    2. For similar pages -- define Visual Studio Templates to generate predefined markup/files, etc.
    3. For similar parts of code -- define code snippets - here is how-to for XAML. They will work at coding-time.