MainViewModel.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System.Collections;
  2. using System.Collections.ObjectModel;
  3. using CommunityToolkit.Mvvm.ComponentModel;
  4. using CommunityToolkit.Mvvm.Input;
  5. using Waaagh.Behaviors;
  6. namespace WpfSample.ViewModels {
  7. internal partial class MainViewModel: ObservableObject {
  8. public MainViewModel() {
  9. Random random = new Random();
  10. for (int i = random.Next(1, 10); i >= 0; --i) {
  11. Groups.Add(new DemoGroupViewModel() {
  12. Name = $"G{i}",
  13. });
  14. }
  15. for (int i = random.Next(1, 10); i >= 0; --i) {
  16. Groups2.Add(new DemoGroupViewModel() {
  17. Name = $"G{i}",
  18. });
  19. }
  20. }
  21. [ObservableProperty]
  22. private string message = string.Empty;
  23. public ObservableCollection<DemoGroupViewModel> Groups { get; } = new ObservableCollection<DemoGroupViewModel>();
  24. public ObservableCollection<DemoGroupViewModel> Groups2 { get; } = new ObservableCollection<DemoGroupViewModel>();
  25. class Test {
  26. public string Name { get; set; } = string.Empty;
  27. }
  28. [RelayCommand]
  29. private void AddGroup() {
  30. Groups.Add(new DemoGroupViewModel() {
  31. Name = $"GX",
  32. });
  33. Groups2.Add(new DemoGroupViewModel() {
  34. Name = $"GY",
  35. });
  36. }
  37. [RelayCommand]
  38. private void AddItem() {
  39. Groups[0].AddItemCommand?.Execute(null);
  40. }
  41. public ItemsDraggable.DoEffectsCallbackHandler DoMoveEffectFunc { get; } = (object sender, ItemsDraggable.DoEffectsCallbackArgs args) => {
  42. object sourceData = args.SourceData;
  43. object? targetData = args.TargetData;
  44. IList sourceCollection = args.SourceCollection;
  45. IList targetCollection = args.TargetCollection;
  46. int oldIndex = sourceCollection.IndexOf(sourceData);
  47. int newIndex = targetCollection.IndexOf(targetData);
  48. if (newIndex == -1) {
  49. newIndex = targetCollection.Count - 1;
  50. }
  51. if (object.ReferenceEquals(sourceCollection, targetCollection)) {
  52. if (oldIndex == newIndex) {
  53. return;
  54. }
  55. // 同个集合, 移除元素后下标可能变化
  56. if (oldIndex < newIndex) {
  57. newIndex -= 1;
  58. }
  59. }
  60. sourceCollection.RemoveAt(oldIndex);
  61. targetCollection.Insert(newIndex + 1, sourceData);
  62. };
  63. }
  64. }