TemplateGenerator.cs 2.7 KB

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