ListBoxPageViewModel.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.ObjectModel;
  3. using System.Linq;
  4. using System.Reactive;
  5. using Avalonia.Controls;
  6. using Avalonia.Controls.Selection;
  7. using ReactiveUI;
  8. namespace ControlCatalog.ViewModels
  9. {
  10. public class ListBoxPageViewModel : ReactiveObject
  11. {
  12. private bool _multiple;
  13. private bool _toggle;
  14. private bool _alwaysSelected;
  15. private bool _autoScrollToSelectedItem = true;
  16. private int _counter;
  17. private ObservableAsPropertyHelper<SelectionMode> _selectionMode;
  18. public ListBoxPageViewModel()
  19. {
  20. Items = new ObservableCollection<string>(Enumerable.Range(1, 10000).Select(i => GenerateItem()));
  21. Selection = new SelectionModel<string>();
  22. Selection.Select(1);
  23. _selectionMode = this.WhenAnyValue(
  24. x => x.Multiple,
  25. x => x.Toggle,
  26. x => x.AlwaysSelected,
  27. (m, t, a) =>
  28. (m ? SelectionMode.Multiple : 0) |
  29. (t ? SelectionMode.Toggle : 0) |
  30. (a ? SelectionMode.AlwaysSelected : 0))
  31. .ToProperty(this, x => x.SelectionMode);
  32. AddItemCommand = ReactiveCommand.Create(() => Items.Add(GenerateItem()));
  33. RemoveItemCommand = ReactiveCommand.Create(() =>
  34. {
  35. while (Selection.Count > 0)
  36. {
  37. Items.Remove(Selection.SelectedItems.First());
  38. }
  39. });
  40. SelectRandomItemCommand = ReactiveCommand.Create(() =>
  41. {
  42. var random = new Random();
  43. using (Selection.BatchUpdate())
  44. {
  45. Selection.Clear();
  46. Selection.Select(random.Next(Items.Count - 1));
  47. }
  48. });
  49. }
  50. public ObservableCollection<string> Items { get; }
  51. public SelectionModel<string> Selection { get; }
  52. public SelectionMode SelectionMode => _selectionMode.Value;
  53. public bool Multiple
  54. {
  55. get => _multiple;
  56. set => this.RaiseAndSetIfChanged(ref _multiple, value);
  57. }
  58. public bool Toggle
  59. {
  60. get => _toggle;
  61. set => this.RaiseAndSetIfChanged(ref _toggle, value);
  62. }
  63. public bool AlwaysSelected
  64. {
  65. get => _alwaysSelected;
  66. set => this.RaiseAndSetIfChanged(ref _alwaysSelected, value);
  67. }
  68. public bool AutoScrollToSelectedItem
  69. {
  70. get => _autoScrollToSelectedItem;
  71. set => this.RaiseAndSetIfChanged(ref _autoScrollToSelectedItem, value);
  72. }
  73. public ReactiveCommand<Unit, Unit> AddItemCommand { get; }
  74. public ReactiveCommand<Unit, Unit> RemoveItemCommand { get; }
  75. public ReactiveCommand<Unit, Unit> SelectRandomItemCommand { get; }
  76. private string GenerateItem() => $"Item {_counter++.ToString()}";
  77. }
  78. }