浏览代码

Implement functionality for added controls in ListBoxPage.xaml.cs

Ivan Kochurkin 6 年之前
父节点
当前提交
c3f0841142
共有 1 个文件被更改,包括 46 次插入6 次删除
  1. 46 6
      samples/ControlCatalog/Pages/ListBoxPage.xaml.cs

+ 46 - 6
samples/ControlCatalog/Pages/ListBoxPage.xaml.cs

@@ -1,9 +1,9 @@
-using System;
-using System.Collections;
-using System.Collections.Generic;
+using System.Collections.ObjectModel;
 using System.Linq;
+using System.Reactive;
 using Avalonia.Controls;
 using Avalonia.Markup.Xaml;
+using ReactiveUI;
 
 namespace ControlCatalog.Pages
 {
@@ -11,9 +11,8 @@ namespace ControlCatalog.Pages
     {
         public ListBoxPage()
         {
-            this.InitializeComponent();
-            DataContext = Enumerable.Range(1, 10).Select(i => $"Item {i}" )
-                .ToArray();
+            InitializeComponent();
+            DataContext = new PageViewModel(this.Find<ListBox>("listBox"));
         }
 
         private void InitializeComponent()
@@ -21,5 +20,46 @@ namespace ControlCatalog.Pages
             AvaloniaXamlLoader.Load(this);
         }
 
+        private class PageViewModel : ReactiveObject
+        {
+            private readonly ListBox _listBox;
+            private int _counter;
+            private SelectionMode _selectionMode;
+
+            public PageViewModel(ListBox listBox)
+            {
+                _listBox = listBox;
+
+                Items = new ObservableCollection<string>(Enumerable.Range(1, 10).Select(i => GenerateItem()));
+
+                AddItemCommand = ReactiveCommand.Create(() => Items.Add(GenerateItem()));
+
+                RemoveItemCommand = ReactiveCommand.Create(() =>
+                {
+                    foreach (string selectedItem in listBox.SelectedItems)
+                    {
+                        Items.Remove(selectedItem);
+                    }
+                });
+            }
+
+            public ObservableCollection<string> Items { get; }
+
+            public ReactiveCommand<Unit, Unit> AddItemCommand { get; }
+
+            public ReactiveCommand<Unit, Unit> RemoveItemCommand { get; }
+
+            public SelectionMode SelectionMode
+            {
+                get => _selectionMode;
+                set
+                {
+                    _listBox.SelectedItems.Clear();
+                    this.RaiseAndSetIfChanged(ref _selectionMode, value);
+                }
+            }
+
+            private string GenerateItem() => $"Item {_counter++}";
+        }
     }
 }