EnumSetting.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using PixiEditor.Helpers.Extensions;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Controls.Primitives;
  10. using System.Windows.Data;
  11. namespace PixiEditor.Models.Tools.ToolSettings.Settings
  12. {
  13. public class EnumSetting<TEnum> : Setting<TEnum, ComboBox>
  14. where TEnum : struct, Enum
  15. {
  16. private int selectedIndex = 0;
  17. /// <summary>
  18. /// Gets or sets the selected Index of the <see cref="ComboBox"/>.
  19. /// </summary>
  20. public int SelectedIndex
  21. {
  22. get => selectedIndex;
  23. set
  24. {
  25. if (SetProperty(ref selectedIndex, value))
  26. {
  27. RaisePropertyChanged(nameof(Value));
  28. }
  29. }
  30. }
  31. /// <summary>
  32. /// Gets or sets the selected value of the <see cref="ComboBox"/>.
  33. /// </summary>
  34. public new TEnum Value
  35. {
  36. get => (TEnum)(SettingControl.SelectedItem as ComboBoxItem).Tag;
  37. set
  38. {
  39. for (int i = 0; i < SettingControl.Items.Count; i++)
  40. {
  41. ComboBoxItem item = SettingControl.Items[i] as ComboBoxItem;
  42. if (item.Tag.Equals(value))
  43. {
  44. SelectedIndex = i;
  45. }
  46. }
  47. }
  48. }
  49. public override Control GenerateControl()
  50. {
  51. return GenerateDropdown();
  52. }
  53. public EnumSetting(string name, string label)
  54. : base(name)
  55. {
  56. Label = label;
  57. }
  58. public EnumSetting(string name, string label, TEnum defaultValue)
  59. : this(name, label)
  60. {
  61. Value = defaultValue;
  62. }
  63. private static ComboBox GenerateDropdown()
  64. {
  65. ComboBox combobox = new ComboBox
  66. {
  67. VerticalAlignment = VerticalAlignment.Center
  68. };
  69. GenerateItems(combobox);
  70. Binding binding = new Binding(nameof(SelectedIndex))
  71. {
  72. Mode = BindingMode.TwoWay
  73. };
  74. combobox.SetBinding(Selector.SelectedIndexProperty, binding);
  75. return combobox;
  76. }
  77. private static void GenerateItems(ComboBox comboBox)
  78. {
  79. TEnum[] values = Enum.GetValues<TEnum>();
  80. foreach (TEnum value in values)
  81. {
  82. ComboBoxItem item = new ComboBoxItem
  83. {
  84. Content = value.GetDescription(),
  85. Tag = value
  86. };
  87. comboBox.Items.Add(item);
  88. }
  89. }
  90. }
  91. }