Skip to content

Instantly share code, notes, and snippets.

@click2install
Last active January 13, 2020 14:37
Show Gist options
  • Save click2install/700c5b43ecc79d54b1e07ef40eece632 to your computer and use it in GitHub Desktop.
Save click2install/700c5b43ecc79d54b1e07ef40eece632 to your computer and use it in GitHub Desktop.
T4 Template for generating a typed C# class of Lazy XAML resources
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Linq" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="System.Xml.Linq" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Xml.Linq" #>
<#@ output extension=".cs" #>
<#
var type = "StreamGeometry";
var genericType= type;
var klass = "Icon";
var path= $@"XamlResources\Icons.xaml";
var doc = XDocument.Load(Host.ResolvePath($@".\{path}"));
#>
using System;
using System.CodeDom.Compiler;
using System.Windows;
using System.Windows.Media;
// NOTE: This file is auto-generated from a T4 Template, any changes made to this file will be lost.
namespace App.Resources
{
[GeneratedCode("T4CodeGenerator", "1.0")]
public static class <#= klass #>Resources
{
<#
var elements = doc.Document.Descendants()
.Where(x => x.Name.LocalName == type)
.OrderBy(x => x.Name.LocalName);
foreach (var element in elements)
{
var key = element.Attributes().First(x => x.Name.LocalName == "Key").Value;
var name = key.Replace("Icon_", "").Replace("_", "");
var field = $"{name[0].ToString().ToLower()}{name.Substring(1)}";
#>
private static Lazy<<#= genericType #>> <#= field #> = new Lazy<<#= genericType #>>(() => (<#= genericType #>)Application.Current.FindResource("<#= key #>"));
/// <summary
/// Retrieves the cached '<#= key #>' <#= type #> resource from <#= path #>.
/// </summary>
public static <#= genericType #> <#= name #> { get => <#= field #>.Value; }
<#
}
#>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment