using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace comal.timesheets { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class StringList : ContentView { private List _editors = new List(); private ImageButton _add; public StringList() { InitializeComponent(); _add = _addbutton; } private void AddBtn_Clicked(object sender, EventArgs e) { _editors.Add(CreateEditor()); LoadLayout(); } private void LoadLayout() { _grid.Children.Clear(); _grid.RowDefinitions.Clear(); foreach (var editor in _editors) { _grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto } ); editor.SetValue(Grid.RowProperty,_grid.RowDefinitions.Count-1); _grid.Children.Add(editor); } if (!_editors.Any()) _grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto } ); _add.SetValue(Grid.RowProperty, _grid.RowDefinitions.Count-1); _add.SetValue(Grid.ColumnProperty, 1); _grid.Children.Add(_add); } private DeleteableEditor CreateEditor(string text = "") { DeleteableEditor editor = new DeleteableEditor(text); editor.OnEditorDeleted += () => { _editors.Remove(editor); LoadLayout(); }; return editor; } public void LoadList(string[] items) { _editors.Clear(); foreach (var item in items) _editors.Add(CreateEditor(item)); LoadLayout(); } public string[] SaveItems() { List items = new List(); foreach (DeleteableEditor entry in _editors) { if (!string.IsNullOrEmpty(entry.Text)) items.Add(entry.Text); } return items.ToArray(); } } public delegate void EditorDeleted(); public class DeleteableEditor : Grid { public event EditorDeleted OnEditorDeleted; public string Text { get; set; } public DeleteableEditor(string text = "") { Text = text; Setup(); } private void Setup() { ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) }); ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); ImageButton img = new ImageButton { Source = "closee.png", HeightRequest = 25, WidthRequest = 25, }; img.Clicked += (o,e) => OnEditorDeleted?.Invoke(); Grid.SetColumn(img, 0); var edt = new Entry(); edt.Text = Text; edt.FontSize = 16; edt.Keyboard = Keyboard.Plain; edt.TextChanged += (sender, e) => { Text = edt.Text; }; Grid.SetColumn(edt, 1); Children.Add(edt); Children.Add(img); } } }