TextField.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Data;
  4. using PixiEditor.Extensions.CommonApi.FlyUI.Events;
  5. namespace PixiEditor.Extensions.FlyUI.Elements;
  6. internal class TextField : LayoutElement
  7. {
  8. private string text;
  9. private string? placeholder;
  10. public event ElementEventHandler TextChanged
  11. {
  12. add => AddEvent(nameof(TextChanged), value);
  13. remove => RemoveEvent(nameof(TextChanged), value);
  14. }
  15. public string Text { get => text; set => SetField(ref text, value); }
  16. public string? Placeholder { get => placeholder; set => SetField(ref placeholder, value); }
  17. public TextField(string text, string? placeholder = null)
  18. {
  19. Text = text;
  20. Placeholder = placeholder ?? string.Empty;
  21. }
  22. protected override Control CreateNativeControl()
  23. {
  24. TextBox textBox = new TextBox();
  25. Binding binding =
  26. new Binding(nameof(Text)) { Source = this, Mode = BindingMode.TwoWay };
  27. textBox.Bind(TextBox.TextProperty, binding);
  28. Binding placeholderBinding =
  29. new Binding(nameof(Placeholder)) { Source = this, Mode = BindingMode.OneWay };
  30. textBox.Bind(TextBox.WatermarkProperty, placeholderBinding);
  31. textBox.Padding = new Thickness(5);
  32. textBox.TextChanged += (s, e) =>
  33. {
  34. RaiseEvent(nameof(TextChanged), new TextEventArgs(textBox.Text));
  35. };
  36. return textBox;
  37. }
  38. protected override IEnumerable<object> GetControlProperties()
  39. {
  40. yield return Text;
  41. yield return Placeholder;
  42. }
  43. protected override void DeserializeControlProperties(List<object> values)
  44. {
  45. Text = (string)values[0];
  46. Placeholder = values.ElementAtOrDefault(1) as string;
  47. }
  48. }