StringList.xaml.cs 2.6 KB

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