MainWindow.xaml.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Net;
  3. using Avalonia;
  4. using Avalonia.Controls;
  5. using Avalonia.Controls.Remote;
  6. using Avalonia.Markup.Xaml;
  7. using Avalonia.Remote.Protocol;
  8. using Avalonia.Remote.Protocol.Designer;
  9. using Avalonia.Remote.Protocol.Viewport;
  10. using Avalonia.Threading;
  11. namespace Previewer
  12. {
  13. public class MainWindow : Window
  14. {
  15. private const string InitialXaml = @"<Window xmlns=""https://github.com/avaloniaui"" Width=""600"" Height=""500"">
  16. <TextBlock>Hello world!</TextBlock>
  17. </Window>";
  18. private IAvaloniaRemoteTransportConnection _connection;
  19. private Control _errorsContainer;
  20. private TextBlock _errors;
  21. private RemoteWidget _remote;
  22. public MainWindow()
  23. {
  24. this.InitializeComponent();
  25. var tb = this.FindControl<TextBox>("Xaml");
  26. tb.Text = InitialXaml;
  27. var scroll = this.FindControl<ScrollViewer>("Remote");
  28. var rem = new Center();
  29. scroll.Content = rem;
  30. _errorsContainer = this.FindControl<Control>("ErrorsContainer");
  31. _errors = this.FindControl<TextBlock>("Errors");
  32. tb.GetObservable(TextBox.TextProperty).Subscribe(text => _connection?.Send(new UpdateXamlMessage
  33. {
  34. Xaml = text
  35. }));
  36. new BsonTcpTransport().Listen(IPAddress.Loopback, 25000, t =>
  37. {
  38. Dispatcher.UIThread.Post(() =>
  39. {
  40. if (_connection != null)
  41. {
  42. _connection.Dispose();
  43. _connection.OnMessage -= OnMessage;
  44. }
  45. _connection = t;
  46. rem.Child = _remote = new RemoteWidget(t);
  47. t.Send(new UpdateXamlMessage
  48. {
  49. Xaml = tb.Text
  50. });
  51. t.OnMessage += OnMessage;
  52. });
  53. });
  54. Title = "Listening on 127.0.0.1:25000";
  55. }
  56. private void OnMessage(IAvaloniaRemoteTransportConnection transport, object obj)
  57. {
  58. Dispatcher.UIThread.Post(() =>
  59. {
  60. if (transport != _connection)
  61. return;
  62. if (obj is UpdateXamlResultMessage result)
  63. {
  64. _errorsContainer.IsVisible = result.Error != null;
  65. _errors.Text = result.Error ?? "";
  66. }
  67. if (obj is RequestViewportResizeMessage resize)
  68. {
  69. _remote.Width = Math.Min(4096, Math.Max(resize.Width, 1));
  70. _remote.Height = Math.Min(4096, Math.Max(resize.Height, 1));
  71. }
  72. });
  73. }
  74. private void InitializeComponent()
  75. {
  76. AvaloniaXamlLoader.Load(this);
  77. }
  78. }
  79. }