Skip to content

Instantly share code, notes, and snippets.

@marckm
Last active August 29, 2015 14:11
Show Gist options
  • Save marckm/ce5c024a5b052e3fd7d7 to your computer and use it in GitHub Desktop.
Save marckm/ce5c024a5b052e3fd7d7 to your computer and use it in GitHub Desktop.
WPF - generate datatemplate to bind VMs to Views using conventions
/// <summary>
/// DEMO CODE !!! TESTING PURPOSE ONLY
/// Generates on the fly the datatemplate to bind VMs to Views
/// </summary>
private void GenerateDataTemplatesForViewModels()
{
// http://www.codeproject.com/Articles/444371/Creating-WPF-Data-Templates-in-Code-The-Right-Way
var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes().ToList();
foreach (var type in assemblyTypes)
{
if (type.FullName.EndsWith("ViewModel"))
{
// we just found a view model
var viewModelType = type;
var vm = viewModelType.Name;
var view = vm.Replace("Model", "");
var viewType = assemblyTypes.FirstOrDefault(t => t.Name.Equals(view));
if (viewType != null)
{
var dataTemplate =
"<DataTemplate DataType=\"{x:Type vm:" + vm + "}\"> " +
"<views:" + view + " />" +
"</DataTemplate>";
const string xamlTemplate = "<DataTemplate DataType=\"{{x:Type vm:{0}}}\"><v:{1} /></DataTemplate>";
var xaml = String.Format(xamlTemplate,
viewModelType.Name,
viewType.Name,
viewModelType.Namespace,
viewType.Namespace);
var context = new ParserContext();
context.XamlTypeMapper = new XamlTypeMapper(new string[0]);
context.XamlTypeMapper.AddMappingProcessingInstruction("vm", viewModelType.Namespace, viewModelType.Assembly.FullName);
context.XamlTypeMapper.AddMappingProcessingInstruction("v", viewType.Namespace, viewType.Assembly.FullName);
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
context.XmlnsDictionary.Add("vm", "vm");
context.XmlnsDictionary.Add("v", "v");
var template = (DataTemplate)XamlReader.Parse(xaml, context);
var key = template.DataTemplateKey;
Application.Current.Resources.Add(key, template);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment