DesignWindowLoader.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Text;
  5. using Avalonia.Controls;
  6. using Avalonia.Controls.Platform;
  7. using Avalonia.Markup.Xaml;
  8. using Avalonia.Styling;
  9. namespace Avalonia.DesignerSupport
  10. {
  11. public class DesignWindowLoader
  12. {
  13. public static Window LoadDesignerWindow(string xaml, string assemblyPath)
  14. {
  15. Window window;
  16. Control control;
  17. using (PlatformManager.DesignerMode())
  18. {
  19. var loader = new AvaloniaXamlLoader();
  20. var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml));
  21. Uri baseUri = null;
  22. if (assemblyPath != null)
  23. {
  24. //Fabricate fake Uri
  25. baseUri =
  26. new Uri("resm:Fake.xaml?assembly=" + Path.GetFileNameWithoutExtension(assemblyPath));
  27. }
  28. var loaded = loader.Load(stream, null, baseUri);
  29. var styles = loaded as Styles;
  30. if (styles != null)
  31. {
  32. var substitute = Design.GetPreviewWith(styles) ??
  33. styles.Select(Design.GetPreviewWith).FirstOrDefault(s => s != null);
  34. if (substitute != null)
  35. {
  36. substitute.Styles.AddRange(styles);
  37. control = substitute;
  38. }
  39. else
  40. control = new StackPanel
  41. {
  42. Children =
  43. {
  44. new TextBlock {Text = "Styles can't be previewed without Design.PreviewWith. Add"},
  45. new TextBlock {Text = "<Design.PreviewWith>"},
  46. new TextBlock {Text = " <Border Padding=20><!-- YOUR CONTROL FOR PREVIEW HERE--></Border>"},
  47. new TextBlock {Text = "<Design.PreviewWith>"},
  48. new TextBlock {Text = "before setters in your first Style"}
  49. }
  50. };
  51. }
  52. else if (loaded is Application)
  53. control = new TextBlock {Text = "Application can't be previewed in design view"};
  54. else
  55. control = (Control) loaded;
  56. window = control as Window;
  57. if (window == null)
  58. {
  59. window = new Window() {Content = (Control)control};
  60. }
  61. if (!window.IsSet(Window.SizeToContentProperty))
  62. window.SizeToContent = SizeToContent.WidthAndHeight;
  63. }
  64. window.Show();
  65. Design.ApplyDesignModeProperties(window, control);
  66. return window;
  67. }
  68. }
  69. }