NumericUpDown.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using System;
  2. using System.Windows;
  3. using System.Windows.Controls;
  4. using System.Windows.Controls.Primitives;
  5. using System.Windows.Data;
  6. using System.Windows.Input;
  7. using System.Windows.Media;
  8. using HandyControl.Data;
  9. using HandyControl.Interactivity;
  10. using HandyControl.Tools;
  11. namespace HandyControl.Controls;
  12. /// <summary>
  13. /// 数值选择控件
  14. /// </summary>
  15. [TemplatePart(Name = ElementTextBox, Type = typeof(TextBox))]
  16. public class NumericUpDown : Control
  17. {
  18. private const string ElementTextBox = "PART_TextBox";
  19. private TextBox _textBox;
  20. public NumericUpDown()
  21. {
  22. CommandBindings.Add(new CommandBinding(ControlCommands.Prev, (s, e) =>
  23. {
  24. if (IsReadOnly) return;
  25. SetCurrentValue(ValueProperty, Value + Increment);
  26. }));
  27. CommandBindings.Add(new CommandBinding(ControlCommands.Next, (s, e) =>
  28. {
  29. if (IsReadOnly) return;
  30. SetCurrentValue(ValueProperty, Value - Increment);
  31. }));
  32. CommandBindings.Add(new CommandBinding(ControlCommands.Clear, (s, e) =>
  33. {
  34. if (IsReadOnly) return;
  35. SetCurrentValue(ValueProperty, ValueBoxes.Double0Box);
  36. }));
  37. }
  38. public override void OnApplyTemplate()
  39. {
  40. if (_textBox != null)
  41. {
  42. _textBox.PreviewKeyDown -= TextBox_PreviewKeyDown;
  43. _textBox.TextChanged -= TextBox_TextChanged;
  44. _textBox.LostFocus -= TextBox_LostFocus;
  45. }
  46. base.OnApplyTemplate();
  47. _textBox = GetTemplateChild(ElementTextBox) as TextBox;
  48. if (_textBox != null)
  49. {
  50. _textBox.SetBinding(SelectionBrushProperty, new Binding(SelectionBrushProperty.Name) { Source = this });
  51. #if NET48_OR_GREATER
  52. _textBox.SetBinding(SelectionTextBrushProperty, new Binding(SelectionTextBrushProperty.Name) { Source = this });
  53. #endif
  54. _textBox.SetBinding(SelectionOpacityProperty, new Binding(SelectionOpacityProperty.Name) { Source = this });
  55. _textBox.SetBinding(CaretBrushProperty, new Binding(CaretBrushProperty.Name) { Source = this });
  56. _textBox.PreviewKeyDown += TextBox_PreviewKeyDown;
  57. _textBox.TextChanged += TextBox_TextChanged;
  58. _textBox.LostFocus += TextBox_LostFocus;
  59. _textBox.Text = CurrentText;
  60. }
  61. }
  62. private void TextBox_LostFocus(object sender, RoutedEventArgs e)
  63. {
  64. if (string.IsNullOrWhiteSpace(_textBox.Text))
  65. {
  66. SetCurrentValue(ValueProperty, ValueBoxes.Double0Box);
  67. }
  68. else if (double.TryParse(_textBox.Text, out double value))
  69. {
  70. SetCurrentValue(ValueProperty, value);
  71. }
  72. else
  73. {
  74. SetText(true);
  75. }
  76. }
  77. private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
  78. {
  79. if (double.TryParse(_textBox.Text, out double value))
  80. {
  81. if (value >= Minimum && value <= Maximum)
  82. {
  83. SetCurrentValue(ValueProperty, value);
  84. }
  85. }
  86. }
  87. private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
  88. {
  89. if (IsReadOnly) return;
  90. if (e.Key == Key.Up)
  91. {
  92. Value += Increment;
  93. }
  94. else if (e.Key == Key.Down)
  95. {
  96. Value -= Increment;
  97. }
  98. }
  99. protected override void OnMouseWheel(MouseWheelEventArgs e)
  100. {
  101. base.OnMouseWheel(e);
  102. if (_textBox.IsFocused && !IsReadOnly)
  103. {
  104. Value += e.Delta > 0 ? Increment : -Increment;
  105. SetText(true);
  106. e.Handled = true;
  107. }
  108. }
  109. private string CurrentText => string.IsNullOrWhiteSpace(ValueFormat)
  110. ? DecimalPlaces.HasValue
  111. ? Value.ToString($"#0.{new string('0', DecimalPlaces.Value)}")
  112. : Value.ToString()
  113. : Value.ToString(ValueFormat);
  114. protected virtual void OnValueChanged(FunctionEventArgs<double> e) => RaiseEvent(e);
  115. /// <summary>
  116. /// 值改变事件
  117. /// </summary>
  118. public static readonly RoutedEvent ValueChangedEvent =
  119. EventManager.RegisterRoutedEvent("ValueChanged", RoutingStrategy.Bubble,
  120. typeof(EventHandler<FunctionEventArgs<double>>), typeof(NumericUpDown));
  121. /// <summary>
  122. /// 值改变事件
  123. /// </summary>
  124. public event EventHandler<FunctionEventArgs<double>> ValueChanged
  125. {
  126. add => AddHandler(ValueChangedEvent, value);
  127. remove => RemoveHandler(ValueChangedEvent, value);
  128. }
  129. /// <summary>
  130. /// 当前值
  131. /// </summary>
  132. public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
  133. nameof(Value), typeof(double), typeof(NumericUpDown),
  134. new FrameworkPropertyMetadata(ValueBoxes.Double0Box, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
  135. OnValueChanged, CoerceValue), ValidateHelper.IsInRangeOfDouble);
  136. private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  137. {
  138. var ctl = (NumericUpDown) d;
  139. var v = (double) e.NewValue;
  140. ctl.SetText();
  141. ctl.OnValueChanged(new FunctionEventArgs<double>(ValueChangedEvent, ctl)
  142. {
  143. Info = v
  144. });
  145. }
  146. private void SetText(bool force = false)
  147. {
  148. if (_textBox != null && (!_textBox.IsFocused || force))
  149. {
  150. _textBox.Text = CurrentText;
  151. _textBox.Select(_textBox.Text.Length, 0);
  152. }
  153. }
  154. private static object CoerceValue(DependencyObject d, object basevalue)
  155. {
  156. var ctl = (NumericUpDown) d;
  157. var minimum = ctl.Minimum;
  158. var num = (double) basevalue;
  159. if (num < minimum)
  160. {
  161. ctl.Value = minimum;
  162. return minimum;
  163. }
  164. var maximum = ctl.Maximum;
  165. if (num > maximum)
  166. {
  167. ctl.Value = maximum;
  168. }
  169. ctl.SetText();
  170. return num > maximum ? maximum : num;
  171. }
  172. /// <summary>
  173. /// 当前值
  174. /// </summary>
  175. public double Value
  176. {
  177. get => (double) GetValue(ValueProperty);
  178. set => SetValue(ValueProperty, value);
  179. }
  180. /// <summary>
  181. /// 最大值
  182. /// </summary>
  183. public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register(
  184. nameof(Maximum), typeof(double), typeof(NumericUpDown), new PropertyMetadata(double.MaxValue, OnMaximumChanged, CoerceMaximum), ValidateHelper.IsInRangeOfDouble);
  185. private static void OnMaximumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  186. {
  187. var ctl = (NumericUpDown) d;
  188. ctl.CoerceValue(MinimumProperty);
  189. ctl.CoerceValue(ValueProperty);
  190. }
  191. private static object CoerceMaximum(DependencyObject d, object basevalue)
  192. {
  193. var minimum = ((NumericUpDown) d).Minimum;
  194. return (double) basevalue < minimum ? minimum : basevalue;
  195. }
  196. /// <summary>
  197. /// 最大值
  198. /// </summary>
  199. public double Maximum
  200. {
  201. get => (double) GetValue(MaximumProperty);
  202. set => SetValue(MaximumProperty, value);
  203. }
  204. /// <summary>
  205. /// 最小值
  206. /// </summary>
  207. public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register(
  208. nameof(Minimum), typeof(double), typeof(NumericUpDown), new PropertyMetadata(double.MinValue, OnMinimumChanged, CoerceMinimum), ValidateHelper.IsInRangeOfDouble);
  209. private static void OnMinimumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  210. {
  211. var ctl = (NumericUpDown) d;
  212. ctl.CoerceValue(MaximumProperty);
  213. ctl.CoerceValue(ValueProperty);
  214. }
  215. private static object CoerceMinimum(DependencyObject d, object basevalue)
  216. {
  217. var maximum = ((NumericUpDown) d).Maximum;
  218. return (double) basevalue > maximum ? maximum : basevalue;
  219. }
  220. /// <summary>
  221. /// 最小值
  222. /// </summary>
  223. public double Minimum
  224. {
  225. get => (double) GetValue(MinimumProperty);
  226. set => SetValue(MinimumProperty, value);
  227. }
  228. /// <summary>
  229. /// 指示每单击一下按钮时增加或减少的数量
  230. /// </summary>
  231. public static readonly DependencyProperty IncrementProperty = DependencyProperty.Register(
  232. nameof(Increment), typeof(double), typeof(NumericUpDown), new PropertyMetadata(ValueBoxes.Double1Box));
  233. /// <summary>
  234. /// 指示每单击一下按钮时增加或减少的数量
  235. /// </summary>
  236. public double Increment
  237. {
  238. get => (double) GetValue(IncrementProperty);
  239. set => SetValue(IncrementProperty, value);
  240. }
  241. /// <summary>
  242. /// 指示要显示的小数位数
  243. /// </summary>
  244. public static readonly DependencyProperty DecimalPlacesProperty = DependencyProperty.Register(
  245. nameof(DecimalPlaces), typeof(int?), typeof(NumericUpDown), new PropertyMetadata(default(int?)));
  246. /// <summary>
  247. /// 指示要显示的小数位数
  248. /// </summary>
  249. public int? DecimalPlaces
  250. {
  251. get => (int?) GetValue(DecimalPlacesProperty);
  252. set => SetValue(DecimalPlacesProperty, value);
  253. }
  254. /// <summary>
  255. /// 指示要显示的数字的格式
  256. /// </summary>
  257. public static readonly DependencyProperty ValueFormatProperty = DependencyProperty.Register(
  258. nameof(ValueFormat), typeof(string), typeof(NumericUpDown), new PropertyMetadata(default(string)));
  259. /// <summary>
  260. /// 指示要显示的数字的格式,这将会覆盖 <see cref="DecimalPlaces"/> 属性
  261. /// </summary>
  262. public string ValueFormat
  263. {
  264. get => (string) GetValue(ValueFormatProperty);
  265. set => SetValue(ValueFormatProperty, value);
  266. }
  267. /// <summary>
  268. /// 是否显示上下调值按钮
  269. /// </summary>
  270. internal static readonly DependencyProperty ShowUpDownButtonProperty = DependencyProperty.Register(
  271. nameof(ShowUpDownButton), typeof(bool), typeof(NumericUpDown), new PropertyMetadata(ValueBoxes.TrueBox));
  272. /// <summary>
  273. /// 是否显示上下调值按钮
  274. /// </summary>
  275. internal bool ShowUpDownButton
  276. {
  277. get => (bool) GetValue(ShowUpDownButtonProperty);
  278. set => SetValue(ShowUpDownButtonProperty, ValueBoxes.BooleanBox(value));
  279. }
  280. /// <summary>
  281. /// 标识 IsReadOnly 依赖属性。
  282. /// </summary>
  283. public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register(
  284. nameof(IsReadOnly), typeof(bool), typeof(NumericUpDown), new PropertyMetadata(ValueBoxes.FalseBox));
  285. /// <summary>
  286. /// 获取或设置一个值,该值指示NumericUpDown是否只读。
  287. /// </summary>
  288. public bool IsReadOnly
  289. {
  290. get => (bool) GetValue(IsReadOnlyProperty);
  291. set => SetValue(IsReadOnlyProperty, ValueBoxes.BooleanBox(value));
  292. }
  293. public static readonly DependencyProperty SelectionBrushProperty =
  294. TextBoxBase.SelectionBrushProperty.AddOwner(typeof(NumericUpDown));
  295. public Brush SelectionBrush
  296. {
  297. get => (Brush) GetValue(SelectionBrushProperty);
  298. set => SetValue(SelectionBrushProperty, value);
  299. }
  300. #if NET48_OR_GREATER
  301. public static readonly DependencyProperty SelectionTextBrushProperty =
  302. TextBoxBase.SelectionTextBrushProperty.AddOwner(typeof(NumericUpDown));
  303. public Brush SelectionTextBrush
  304. {
  305. get => (Brush) GetValue(SelectionTextBrushProperty);
  306. set => SetValue(SelectionTextBrushProperty, value);
  307. }
  308. #endif
  309. public static readonly DependencyProperty SelectionOpacityProperty =
  310. TextBoxBase.SelectionOpacityProperty.AddOwner(typeof(NumericUpDown));
  311. public double SelectionOpacity
  312. {
  313. get => (double) GetValue(SelectionOpacityProperty);
  314. set => SetValue(SelectionOpacityProperty, value);
  315. }
  316. public static readonly DependencyProperty CaretBrushProperty =
  317. TextBoxBase.CaretBrushProperty.AddOwner(typeof(NumericUpDown));
  318. public Brush CaretBrush
  319. {
  320. get => (Brush) GetValue(CaretBrushProperty);
  321. set => SetValue(CaretBrushProperty, value);
  322. }
  323. }