TemplateGenerator.cs 2.3 KB

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