1
0

NativeTextBox.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using Avalonia.Controls;
  3. using Avalonia.Platform;
  4. namespace IntegrationTestApp.Embedding;
  5. internal class NativeTextBox : NativeControlHost
  6. {
  7. private ContextMenu? _contextMenu;
  8. private INativeTextBoxImpl? _impl;
  9. private TextBlock _tipTextBlock;
  10. private string _initialText = string.Empty;
  11. public NativeTextBox()
  12. {
  13. _tipTextBlock = new TextBlock
  14. {
  15. Text = "Avalonia ToolTip",
  16. Name = "NativeTextBoxToolTip",
  17. };
  18. ToolTip.SetTip(this, _tipTextBlock);
  19. ToolTip.SetShowDelay(this, 1000);
  20. ToolTip.SetServiceEnabled(this, false);
  21. }
  22. public string Text
  23. {
  24. get => _impl?.Text ?? _initialText;
  25. set
  26. {
  27. if (_impl is not null)
  28. _impl.Text = value;
  29. else
  30. _initialText = value;
  31. }
  32. }
  33. public static INativeTextBoxFactory? Factory { get; set; }
  34. protected override IPlatformHandle CreateNativeControlCore(IPlatformHandle parent)
  35. {
  36. if (Factory is null)
  37. return base.CreateNativeControlCore(parent);
  38. _impl = Factory.CreateControl(parent);
  39. _impl.Text = _initialText;
  40. _impl.ContextMenuRequested += OnContextMenuRequested;
  41. _impl.Hovered += OnHovered;
  42. _impl.PointerExited += OnPointerExited;
  43. return _impl.Handle;
  44. }
  45. protected override void DestroyNativeControlCore(IPlatformHandle control)
  46. {
  47. base.DestroyNativeControlCore(control);
  48. }
  49. private void OnContextMenuRequested(object? sender, EventArgs e)
  50. {
  51. if (_contextMenu is null)
  52. {
  53. var menuItem = new MenuItem { Header = "Custom Menu Item" };
  54. menuItem.Click += (s, e) => _impl!.Text = "Context menu item clicked";
  55. _contextMenu = new ContextMenu
  56. {
  57. Name = "NativeTextBoxContextMenu",
  58. Items = { menuItem }
  59. };
  60. }
  61. ToolTip.SetIsOpen(this, false);
  62. _contextMenu.Open(this);
  63. }
  64. private void OnHovered(object? sender, EventArgs e)
  65. {
  66. ToolTip.SetIsOpen(this, true);
  67. }
  68. private void OnPointerExited(object? sender, EventArgs e)
  69. {
  70. ToolTip.SetIsOpen(this, false);
  71. }
  72. }