CheckBox.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System.Windows.Media;
  2. namespace System.Windows.Forms
  3. {
  4. public class CheckBox : ToggleButtonBase
  5. {
  6. private static System.Windows.Controls.ControlTemplate toggleButtonTemplate = (System.Windows.Controls.ControlTemplate)System.Windows.Markup.XamlReader.Parse(
  7. "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' TargetType =\"CheckBox\">" +
  8. "<ToggleButton IsChecked=\"{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}}\" >" +
  9. "<Image Name=\"image\" Width=\"16\" Height=\"16\" />" +
  10. "</ToggleButton>" +
  11. "</ControlTemplate>");
  12. private static System.Windows.Controls.ControlTemplate checkBoxTemplate = (System.Windows.Controls.ControlTemplate)System.Windows.Markup.XamlReader.Parse(
  13. "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' TargetType =\"CheckBox\">" +
  14. "<CheckBox IsChecked=\"{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}}\" >" +
  15. "<ContentPresenter/>" +
  16. "</CheckBox>" +
  17. "</ControlTemplate>");
  18. private System.Windows.Controls.TextBlock textBlock;
  19. protected new System.Windows.Controls.CheckBox control { get; }
  20. private Appearance appearance;
  21. public Appearance Appearance
  22. {
  23. get => appearance;
  24. set
  25. {
  26. if (value != appearance)
  27. {
  28. appearance = value;
  29. control.Template = value == Appearance.Button ? toggleButtonTemplate : checkBoxTemplate;
  30. control.ApplyTemplate();
  31. }
  32. }
  33. }
  34. protected override void UpdateControlImage(ImageSource image)
  35. {
  36. if (Appearance == Appearance.Button)
  37. {
  38. var img = control.Template.FindName("image", control) as System.Windows.Controls.Image;
  39. img.Source = image;
  40. img.Visibility = image != null ? Visibility.Visible : Visibility.Collapsed;
  41. }
  42. }
  43. protected override void OnEnabledChanged(EventArgs e)
  44. {
  45. base.OnEnabledChanged(e);
  46. textBlock.Opacity = Enabled ? 1 : 0.5;
  47. }
  48. public CheckBox()
  49. {
  50. control = new();
  51. SetControl(control);
  52. textBlock = new();
  53. textBlock.TextWrapping = TextWrapping.Wrap;
  54. control.Content = textBlock;
  55. }
  56. }
  57. }