StringList.xaml.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Xamarin.Forms;
  7. using Xamarin.Forms.Xaml;
  8. using static Android.Content.ClipData;
  9. namespace comal.timesheets
  10. {
  11. [XamlCompilation(XamlCompilationOptions.Compile)]
  12. public partial class StringList : ContentView
  13. {
  14. public StringList()
  15. {
  16. InitializeComponent();
  17. }
  18. private void AddBtn_Clicked(object sender, EventArgs e)
  19. {
  20. stackLayout.Children.Add(
  21. CreateEditor()
  22. );
  23. }
  24. private DeleteableEditor CreateEditor(string text = "")
  25. {
  26. DeleteableEditor editor = new DeleteableEditor(text);
  27. editor.OnEditorDeleted += () => { stackLayout.Children.Remove(editor); };
  28. return editor;
  29. }
  30. public void LoadList(string[] items)
  31. {
  32. foreach (var item in items)
  33. {
  34. stackLayout.Children.Add(CreateEditor(item));
  35. }
  36. }
  37. public string[] SaveItems()
  38. {
  39. List<string> items = new List<string>();
  40. foreach (DeleteableEditor entry in stackLayout.Children)
  41. {
  42. if (!string.IsNullOrEmpty(entry.Text))
  43. items.Add(entry.Text);
  44. }
  45. return items.ToArray();
  46. }
  47. }
  48. public delegate void EditorDeleted();
  49. public class DeleteableEditor : Grid
  50. {
  51. public event EditorDeleted OnEditorDeleted;
  52. public string Text { get; set; }
  53. public DeleteableEditor(string text = "")
  54. {
  55. Text = text;
  56. Setup();
  57. }
  58. private void Setup()
  59. {
  60. ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
  61. ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
  62. var edt = new Entry();
  63. edt.Text = Text;
  64. edt.FontSize = 16;
  65. edt.TextChanged += (sender, e) =>
  66. {
  67. Text = edt.Text;
  68. };
  69. Grid.SetColumn(edt, 0);
  70. Image img = new Image { Source = "closee.png", HeightRequest = 20, WidthRequest = 20 };
  71. img.GestureRecognizers.Add(new TapGestureRecognizer { Command = new Command(Close) });
  72. Grid.SetColumn(img, 1);
  73. Children.Add(edt);
  74. Children.Add(img);
  75. }
  76. private void Close(object obj)
  77. {
  78. OnEditorDeleted?.Invoke();
  79. }
  80. }
  81. }