TemplateGenerator.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. namespace InABox.WPF
  5. {
  6. public static class TemplateGenerator
  7. {
  8. /// <summary>
  9. /// Creates a data-template that uses the given delegate to create new instances.
  10. /// </summary>
  11. public static DataTemplate CreateDataTemplate(Func<object?> factory)
  12. {
  13. if (factory == null)
  14. throw new ArgumentNullException("factory");
  15. var frameworkElementFactory = new FrameworkElementFactory(typeof(_TemplateGeneratorControl));
  16. frameworkElementFactory.SetValue(_TemplateGeneratorControl.FactoryProperty, factory);
  17. var dataTemplate = new DataTemplate(typeof(DependencyObject));
  18. dataTemplate.VisualTree = frameworkElementFactory;
  19. return dataTemplate;
  20. }
  21. /// <summary>
  22. /// Creates a control-template that uses the given delegate to create new instances.
  23. /// </summary>
  24. public static ControlTemplate CreateControlTemplate(Type controlType, Func<object?> factory)
  25. {
  26. if (controlType == null)
  27. throw new ArgumentNullException("controlType");
  28. if (factory == null)
  29. throw new ArgumentNullException("factory");
  30. var frameworkElementFactory = new FrameworkElementFactory(typeof(_TemplateGeneratorControl));
  31. frameworkElementFactory.SetValue(_TemplateGeneratorControl.FactoryProperty, factory);
  32. var controlTemplate = new ControlTemplate(controlType);
  33. controlTemplate.VisualTree = frameworkElementFactory;
  34. return controlTemplate;
  35. }
  36. private sealed class _TemplateGeneratorControl :
  37. ContentControl
  38. {
  39. internal static readonly DependencyProperty FactoryProperty = DependencyProperty.Register("Factory", typeof(Func<object?>),
  40. typeof(_TemplateGeneratorControl), new PropertyMetadata(null, _FactoryChanged));
  41. private static void _FactoryChanged(DependencyObject instance, DependencyPropertyChangedEventArgs args)
  42. {
  43. var control = (_TemplateGeneratorControl)instance;
  44. var factory = (Func<object?>)args.NewValue;
  45. if (factory != null)
  46. control.Content = factory();
  47. }
  48. }
  49. }
  50. }