DesignWindowLoader.cs 3.1 KB

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