EditorViewModel.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using Avalonia.Threading;
  2. namespace XamlTestApplication.ViewModels
  3. {
  4. using ReactiveUI;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Collections.ObjectModel;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. public class ShellViewModel : ReactiveObject
  12. {
  13. private ShellViewModel()
  14. {
  15. documents = new ObservableCollection<EditorViewModel>();
  16. AddDocumentCommand = ReactiveCommand.Create();
  17. AddDocumentCommand.Subscribe(_ =>
  18. {
  19. Documents.Add(new EditorViewModel());
  20. });
  21. GCCommand = ReactiveCommand.Create();
  22. GCCommand.Subscribe(_ =>
  23. {
  24. GC.Collect();
  25. });
  26. }
  27. public static ShellViewModel Instance = new ShellViewModel();
  28. private ObservableCollection<EditorViewModel> documents;
  29. public ObservableCollection<EditorViewModel> Documents
  30. {
  31. get { return documents; }
  32. set { this.RaiseAndSetIfChanged(ref documents, value); }
  33. }
  34. private EditorViewModel selectedDocument;
  35. public EditorViewModel SelectedDocument
  36. {
  37. get { return selectedDocument; }
  38. set { this.RaiseAndSetIfChanged(ref selectedDocument, value); }
  39. }
  40. private int instanceCount;
  41. public int InstanceCount
  42. {
  43. get { return instanceCount; }
  44. set { this.RaiseAndSetIfChanged(ref instanceCount, value); }
  45. }
  46. public ReactiveCommand<object> AddDocumentCommand { get; }
  47. public ReactiveCommand<object> GCCommand { get; }
  48. }
  49. public class EditorViewModel : ReactiveObject
  50. {
  51. private static int InstanceCount = 0;
  52. public EditorViewModel()
  53. {
  54. InstanceCount++;
  55. ShellViewModel.Instance.InstanceCount = InstanceCount;
  56. text = "This is some text.";
  57. CloseCommand = ReactiveCommand.Create();
  58. CloseCommand.Subscribe(_ =>
  59. {
  60. ShellViewModel.Instance.Documents.Remove(this);
  61. });
  62. }
  63. ~EditorViewModel()
  64. {
  65. //System.Console.WriteLine("EVM Destructed");
  66. InstanceCount--;
  67. Dispatcher.UIThread.InvokeAsync(() =>
  68. {
  69. ShellViewModel.Instance.InstanceCount = InstanceCount;
  70. });
  71. }
  72. private string text;
  73. public string Text
  74. {
  75. get { return text; }
  76. set { this.RaiseAndSetIfChanged(ref text, value); }
  77. }
  78. public ReactiveCommand<object> CloseCommand { get; }
  79. }
  80. }