-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathUpDownBase.cs
More file actions
400 lines (324 loc) · 13.4 KB
/
UpDownBase.cs
File metadata and controls
400 lines (324 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
using System.ComponentModel;
using System.Globalization;
namespace MaterialDesignThemes.Wpf;
using System.Diagnostics.CodeAnalysis;
#if NET8_0_OR_GREATER
using System.Numerics;
public class UpDownBase<T> : UpDownBase
where T : INumber<T>, IMinMaxValue<T>
{
private static readonly Type SelfType = typeof(UpDownBase<T>);
private static UpDownBase<T> ToUpDownBase(DependencyObject dependencyObject) => (UpDownBase<T>)dependencyObject;
private static T MinValue => T.MinValue;
private static T MaxValue => T.MaxValue;
private static T One => T.One;
private static T Max(T value1, T value2) => T.Max(value1, value2);
private static T Clamp(T value, T min, T max) => T.Clamp(value, min, max);
private static T Add(T value1, T value2) => value1 + value2;
private static T Subtract(T value1, T value2) => value1 - value2;
private static bool TryParse(string text, IFormatProvider? formatProvider, [MaybeNullWhen(false)] out T value)
=> T.TryParse(text, formatProvider, out value);
private static int Compare(T value1, T value2) => value1.CompareTo(value2);
#else
public class UpDownBase<T, TArithmetic> : UpDownBase
where TArithmetic : IArithmetic<T>, new()
{
private static readonly Type SelfType = typeof(UpDownBase<T, TArithmetic>);
private static readonly TArithmetic _arithmetic = new();
private static UpDownBase<T, TArithmetic> ToUpDownBase(DependencyObject dependencyObject) => (UpDownBase<T, TArithmetic>)dependencyObject;
private static T MinValue => _arithmetic.MinValue();
private static T MaxValue => _arithmetic.MaxValue();
private static T One => _arithmetic.One();
private static T Max(T value1, T value2) => _arithmetic.Max(value1, value2);
private static T Clamp(T value, T min, T max) => _arithmetic.Max(_arithmetic.Min(value, max), min);
private static T Add(T value1, T value2) => _arithmetic.Add(value1, value2);
private static T Subtract(T value1, T value2) => _arithmetic.Subtract(value1, value2);
private static bool TryParse(string text, IFormatProvider? formatProvider, [NotNullWhen(true)] out T value)
=> _arithmetic.TryParse(text, formatProvider, out value);
private static int Compare(T value1, T value2) => _arithmetic.Compare(value1, value2);
#endif
#region DependencyProperties
#region DependencyProperty : MinimumProperty
public virtual T Minimum
{
get => (T)GetValue(MinimumProperty);
set => SetValue(MinimumProperty, value);
}
public static readonly DependencyProperty MinimumProperty =
DependencyProperty.Register(nameof(Minimum), typeof(T), SelfType, new PropertyMetadata(MinValue, OnMinimumChanged));
private static void OnMinimumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctrl = ToUpDownBase(d);
ctrl.CoerceValue(MaximumProperty);
ctrl.CoerceValue(ValueProperty);
}
#endregion DependencyProperty : MinimumProperty
#region DependencyProperty : MaximumProperty
public T Maximum
{
get => (T)GetValue(MaximumProperty);
set => SetValue(MaximumProperty, value);
}
public static readonly DependencyProperty MaximumProperty =
DependencyProperty.Register(nameof(Maximum), typeof(T), SelfType, new PropertyMetadata(MaxValue, OnMaximumChanged, CoerceMaximum));
private static void OnMaximumChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var upDownBase = ToUpDownBase(d);
upDownBase.CoerceValue(ValueProperty);
}
private static object? CoerceMaximum(DependencyObject d, object? value)
{
if (value is T numericValue)
{
var upDownBase = ToUpDownBase(d);
return Max(upDownBase.Minimum, numericValue);
}
return value;
}
#endregion DependencyProperty : MaximumProperty
#region DependencyProperty : ValueProperty
public T Value
{
get => (T)GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register(nameof(Value), typeof(T), SelfType, new FrameworkPropertyMetadata(default(T), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnNumericValueChanged, CoerceNumericValue));
private static void OnNumericValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var upDownBase = ToUpDownBase(d);
var args = new RoutedPropertyChangedEventArgs<T>((T)e.OldValue, (T)e.NewValue)
{
RoutedEvent = ValueChangedEvent
};
upDownBase.RaiseEvent(args);
if (upDownBase._textBoxField is { } textBox)
{
textBox.Text = e.NewValue.ToString();
}
upDownBase.UpdateDecreaseButtonEnabled();
upDownBase.UpdateIncreaseButtonEnabled();
}
private void UpdateIncreaseButtonEnabled()
{
if (_increaseButton is { } increaseButton)
{
increaseButton.IsEnabled = Compare(Value, Maximum) < 0;
}
}
private void UpdateDecreaseButtonEnabled()
{
if (_decreaseButton is { } decreaseButton)
{
decreaseButton.IsEnabled = Compare(Value, Minimum) > 0;
}
}
private static object? CoerceNumericValue(DependencyObject d, object? value)
{
if (value is T numericValue)
{
var upDownBase = ToUpDownBase(d);
numericValue = upDownBase.ClampValue(numericValue);
return numericValue;
}
return value;
}
#endregion ValueProperty
#region DependencyProperty : ValueStep
/// <summary>
/// The step of value for each increase or decrease
/// </summary>
public T ValueStep
{
get => (T)GetValue(ValueStepProperty);
set => SetValue(ValueStepProperty, value);
}
public static readonly DependencyProperty ValueStepProperty =
DependencyProperty.Register(nameof(ValueStep), typeof(T), SelfType, new PropertyMetadata(One));
#endregion
#region DependencyProperty : AllowChangeOnScroll
public bool AllowChangeOnScroll
{
get => (bool)GetValue(AllowChangeOnScrollProperty);
set => SetValue(AllowChangeOnScrollProperty, value);
}
public static readonly DependencyProperty AllowChangeOnScrollProperty =
DependencyProperty.Register(nameof(AllowChangeOnScroll), typeof(bool), SelfType, new PropertyMetadata(false));
#endregion
#endregion DependencyProperties
#region Event : ValueChangedEvent
[Category("Behavior")]
public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent(nameof(ValueChanged), RoutingStrategy.Bubble, typeof(RoutedPropertyChangedEventHandler<T>), SelfType);
public event RoutedPropertyChangedEventHandler<T> ValueChanged
{
add => AddHandler(ValueChangedEvent, value);
remove => RemoveHandler(ValueChangedEvent, value);
}
#endregion Event : ValueChangedEvent
public override void OnApplyTemplate()
{
if (_increaseButton != null)
_increaseButton.Click -= IncreaseButtonOnClick;
if (_decreaseButton != null)
_decreaseButton.Click -= DecreaseButtonOnClick;
if (_textBoxField != null)
{
_textBoxField.TextChanged -= OnTextBoxTextChanged;
_textBoxField.LostFocus -= OnTextBoxLostFocus;
}
base.OnApplyTemplate();
if (_increaseButton != null)
{
_increaseButton.Click += IncreaseButtonOnClick;
UpdateIncreaseButtonEnabled();
}
if (_decreaseButton != null)
{
_decreaseButton.Click += DecreaseButtonOnClick;
UpdateDecreaseButtonEnabled();
}
if (_textBoxField != null)
{
_textBoxField.TextChanged += OnTextBoxTextChanged;
_textBoxField.LostFocus += OnTextBoxLostFocus;
_textBoxField.Text = Value?.ToString();
}
}
private void OnTextBoxLostFocus(object sender, EventArgs e)
{
if (_textBoxField is { } textBoxField)
{
textBoxField.Text = Value?.ToString();
}
}
private void OnTextBoxTextChanged(object sender, EventArgs e)
{
if (_textBoxField is { } textBoxField)
{
if (TryParse(textBoxField.Text, CultureInfo.CurrentUICulture, out T? value))
{
SetCurrentValue(ValueProperty, ClampValue(value));
}
}
}
private void IncreaseButtonOnClick(object sender, RoutedEventArgs e) => OnIncrease();
private void DecreaseButtonOnClick(object sender, RoutedEventArgs e) => OnDecrease();
private void OnIncrease() => SetCurrentValue(ValueProperty, Clamp(Add(Value, ValueStep), Minimum, Maximum));
private void OnDecrease() => SetCurrentValue(ValueProperty, Clamp(Subtract(Value, ValueStep), Minimum, Maximum));
private T ClampValue(T value)
=> Clamp(value, Minimum, Maximum);
protected override void OnPreviewKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Up)
{
OnIncrease();
e.Handled = true;
}
else if (e.Key == Key.Down)
{
OnDecrease();
e.Handled = true;
}
base.OnPreviewKeyDown(e);
}
protected override void OnPreviewMouseWheel(MouseWheelEventArgs e)
{
if (IsKeyboardFocusWithin && AllowChangeOnScroll)
{
if (e.Delta > 0)
{
OnIncrease();
}
else if (e.Delta < 0)
{
OnDecrease();
}
e.Handled = true;
}
base.OnPreviewMouseWheel(e);
}
}
[TemplatePart(Name = IncreaseButtonPartName, Type = typeof(RepeatButton))]
[TemplatePart(Name = DecreaseButtonPartName, Type = typeof(RepeatButton))]
[TemplatePart(Name = TextBoxPartName, Type = typeof(TextBox))]
public class UpDownBase : Control
{
public const string IncreaseButtonPartName = "PART_IncreaseButton";
public const string DecreaseButtonPartName = "PART_DecreaseButton";
public const string TextBoxPartName = "PART_TextBox";
protected TextBox? _textBoxField;
protected RepeatButton? _decreaseButton;
protected RepeatButton? _increaseButton;
static UpDownBase()
{
EventManager.RegisterClassHandler(typeof(UpDownBase), GotFocusEvent, new RoutedEventHandler(OnGotFocus));
}
// Based on work in MahApps
// https://github.com/MahApps/MahApps.Metro/blob/f7ba30586e9670f07c2f7b6553d129a9e32fc673/src/MahApps.Metro/Controls/NumericUpDown.cs#L966
private static void OnGotFocus(object sender, RoutedEventArgs e)
{
// When NumericUpDown gets logical focus, select the text inside us.
// If we're an editable NumericUpDown, forward focus to the TextBox element
if (!e.Handled)
{
var numericUpDown = (UpDownBase)sender;
if (numericUpDown.Focusable && e.OriginalSource == numericUpDown)
{
// MoveFocus takes a TraversalRequest as its argument.
var focusDirection = Keyboard.Modifiers.HasFlag(ModifierKeys.Shift)
? FocusNavigationDirection.Previous
: FocusNavigationDirection.Next;
var request = new TraversalRequest(focusDirection);
// Gets the element with keyboard focus.
// And change the keyboard focus.
if (Keyboard.FocusedElement is UIElement elementWithFocus)
{
elementWithFocus.MoveFocus(request);
}
else
{
numericUpDown.Focus();
}
e.Handled = true;
}
}
}
public override void OnApplyTemplate()
{
_increaseButton = GetTemplateChild(IncreaseButtonPartName) as RepeatButton;
_decreaseButton = GetTemplateChild(DecreaseButtonPartName) as RepeatButton;
_textBoxField = GetTemplateChild(TextBoxPartName) as TextBox;
base.OnApplyTemplate();
}
public void SelectAll() => _textBoxField?.SelectAll();
public object? IncreaseContent
{
get => GetValue(IncreaseContentProperty);
set => SetValue(IncreaseContentProperty, value);
}
// Using a DependencyProperty as the backing store for IncreaseContent. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IncreaseContentProperty =
DependencyProperty.Register(nameof(IncreaseContent), typeof(object), typeof(UpDownBase), new PropertyMetadata(null));
public object? DecreaseContent
{
get => GetValue(DecreaseContentProperty);
set => SetValue(DecreaseContentProperty, value);
}
// Using a DependencyProperty as the backing store for DecreaseContent. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DecreaseContentProperty =
DependencyProperty.Register(nameof(DecreaseContent), typeof(object), typeof(UpDownBase), new PropertyMetadata(null));
}
#if !NET8_0_OR_GREATER
public interface IArithmetic<T>
{
T Add(T value1, T value2);
T Subtract(T value1, T value2);
int Compare(T value1, T value2);
T MinValue();
T MaxValue();
T One();
T Max(T value1, T value2);
T Min(T value1, T value2);
bool TryParse(string text, IFormatProvider? formatProvider, [NotNullWhen(true)] out T value);
}
#endif