Label.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System.Drawing;
  2. namespace System.Windows.Forms
  3. {
  4. public class Label : Control
  5. {
  6. private System.Windows.Controls.TextBlock textBlock;
  7. protected new System.Windows.Controls.Label control { get; }
  8. public override bool AutoSize
  9. {
  10. get => base.AutoSize;
  11. set
  12. {
  13. if (base.AutoSize != value)
  14. {
  15. base.AutoSize = value;
  16. // when AutoSize is false, update the control size (case: FR LabelControl wrong scale when AutoSize is set to False after setting Width and Height)
  17. if (!value)
  18. {
  19. SetControlWidth(Width);
  20. SetControlHeight(Height);
  21. }
  22. }
  23. textBlock.TextWrapping = value ? TextWrapping.NoWrap : TextWrapping.Wrap;
  24. }
  25. }
  26. public override string Text
  27. {
  28. get => textBlock.Text;
  29. set
  30. {
  31. bool needFixLeft = AutoSize && control.FlowDirection == FlowDirection.RightToLeft;
  32. var width = needFixLeft ? Width : 0;
  33. textBlock.Text = value?.Replace("\t", "");
  34. base.Text = textBlock.Text;
  35. if (needFixLeft)
  36. {
  37. // reset WPF measure cache
  38. control.Measure(new Size(10000, 10000));
  39. Left += width - Width;
  40. }
  41. }
  42. }
  43. private ContentAlignment textAlign;
  44. public ContentAlignment TextAlign
  45. {
  46. get => textAlign;
  47. set
  48. {
  49. textAlign = value;
  50. Helper.GetContentAlignment(value, out System.Windows.HorizontalAlignment h, out System.Windows.VerticalAlignment v);
  51. control.HorizontalContentAlignment = h;
  52. control.VerticalContentAlignment = v;
  53. }
  54. }
  55. public FlatStyle FlatStyle { get; set; }
  56. public bool UseCompatibleTextRendering { get; set; }
  57. public Label()
  58. {
  59. control = new();
  60. SetControl(control);
  61. textBlock = new();
  62. control.Content = textBlock;
  63. // match winforms appearance
  64. Padding = new Padding(2, 0, 0, 0);
  65. textBlock.Margin = new Thickness(0);
  66. AutoSize = false;
  67. }
  68. }
  69. }