aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/SideChains/WpfExtendedToolKit/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit/Primitives/UpDownBase.cs
blob: b49372d39977b7373ebe1a1e4facc57a58541b84 (plain)
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
/*************************************************************************************

   Extended WPF Toolkit

   Copyright (C) 2007-2013 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license 

   For more features, controls, and fast professional support,
   pick up the Plus Edition at http://xceed.com/wpf_toolkit

   Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids

  ***********************************************************************************/

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using Xceed.Wpf.Toolkit.Core;
using Xceed.Wpf.Toolkit.Core.Input;
using System.Globalization;
using System.Windows.Threading;

namespace Xceed.Wpf.Toolkit.Primitives
{
  [TemplatePart( Name = PART_TextBox, Type = typeof( TextBox ) )]
  [TemplatePart( Name = PART_Spinner, Type = typeof( Spinner ) )]
  public abstract class UpDownBase<T> : InputBase, IValidateInput
  {
    #region Members

    /// <summary>
    /// Name constant for Text template part.
    /// </summary>
    internal const string PART_TextBox = "PART_TextBox";

    /// <summary>
    /// Name constant for Spinner template part.
    /// </summary>
    internal const string PART_Spinner = "PART_Spinner";

    internal bool _isTextChangedFromUI;

    /// <summary>
    /// Flags if the Text and Value properties are in the process of being sync'd
    /// </summary>
    private bool _isSyncingTextAndValueProperties;
    private bool _internalValueSet;

    #endregion //Members

    #region Properties

    protected Spinner Spinner
    {
      get;
      private set;
    }
    protected TextBox TextBox
    {
      get;
      private set;
    }

    #region AllowSpin

    public static readonly DependencyProperty AllowSpinProperty = DependencyProperty.Register( "AllowSpin", typeof( bool ), typeof( UpDownBase<T> ),

new UIPropertyMetadata( true ) );
    public bool AllowSpin
    {
      get
      {
        return (bool)GetValue( AllowSpinProperty );
      }
      set
      {
        SetValue( AllowSpinProperty, value );
      }
    }

    #endregion //AllowSpin

    #region ButtonSpinnerLocation

    public static readonly DependencyProperty ButtonSpinnerLocationProperty = DependencyProperty.Register( "ButtonSpinnerLocation", typeof( Location

), typeof( UpDownBase<T> ), new UIPropertyMetadata( Location.Right ) );
    public Location ButtonSpinnerLocation
    {
      get
      {
        return (Location)GetValue( ButtonSpinnerLocationProperty );
      }
      set
      {
        SetValue( ButtonSpinnerLocationProperty, value );
      }
    }

    #endregion //ButtonSpinnerLocation

    #region ClipValueToMinMax

    public static readonly DependencyProperty ClipValueToMinMaxProperty = DependencyProperty.Register( "ClipValueToMinMax", typeof( bool ), typeof(

UpDownBase<T> ), new UIPropertyMetadata( false ) );
    public bool ClipValueToMinMax
    {
      get
      {
        return (bool)GetValue( ClipValueToMinMaxProperty );
      }
      set
      {
        SetValue( ClipValueToMinMaxProperty, value );
      }
    }

    #endregion //ClipValueToMinMax

    #region DisplayDefaultValueOnEmptyText

    public static readonly DependencyProperty DisplayDefaultValueOnEmptyTextProperty = DependencyProperty.Register( "DisplayDefaultValueOnEmptyText",

typeof( bool ), typeof( UpDownBase<T> ), new UIPropertyMetadata( false, OnDisplayDefaultValueOnEmptyTextChanged ) );
    public bool DisplayDefaultValueOnEmptyText
    {
      get
      {
        return (bool)GetValue( DisplayDefaultValueOnEmptyTextProperty );
      }
      set
      {
        SetValue( DisplayDefaultValueOnEmptyTextProperty, value );
      }
    }

    private static void OnDisplayDefaultValueOnEmptyTextChanged( DependencyObject source, DependencyPropertyChangedEventArgs args )
    {
      ((UpDownBase<T>)source).OnDisplayDefaultValueOnEmptyTextChanged( (bool)args.OldValue, (bool)args.NewValue );
    }

    private void OnDisplayDefaultValueOnEmptyTextChanged( bool oldValue, bool newValue )
    {
      if( this.IsInitialized && string.IsNullOrEmpty( Text ) )
      {
        this.SyncTextAndValueProperties( false, Text );
      }
    }

    #endregion //DisplayDefaultValueOnEmptyText

    #region DefaultValue

    public static readonly DependencyProperty DefaultValueProperty = DependencyProperty.Register( "DefaultValue", typeof( T ), typeof( UpDownBase<T>

), new UIPropertyMetadata( default( T ), OnDefaultValueChanged ) );
    public T DefaultValue
    {
      get
      {
        return (T)GetValue( DefaultValueProperty );
      }
      set
      {
        SetValue( DefaultValueProperty, value );
      }
    }

    private static void OnDefaultValueChanged( DependencyObject source, DependencyPropertyChangedEventArgs args )
    {
      ((UpDownBase<T>)source).OnDefaultValueChanged( (T)args.OldValue, (T)args.NewValue );
    }

    private void OnDefaultValueChanged( T oldValue, T newValue )
    {
      if( this.IsInitialized && string.IsNullOrEmpty( Text ) )
      {
        this.SyncTextAndValueProperties( true, Text );
      }
    }

    #endregion //DefaultValue

    #region Maximum

    public static readonly DependencyProperty MaximumProperty = DependencyProperty.Register( "Maximum", typeof( T ), typeof( UpDownBase<T> ), new

UIPropertyMetadata( default( T ), OnMaximumChanged, OnCoerceMaximum ) );
    public T Maximum
    {
      get
      {
        return (T)GetValue( MaximumProperty );
      }
      set
      {
        SetValue( MaximumProperty, value );
      }
    }

    private static void OnMaximumChanged( DependencyObject o, DependencyPropertyChangedEventArgs e )
    {
      UpDownBase<T> upDown = o as UpDownBase<T>;
      if( upDown != null )
        upDown.OnMaximumChanged( (T)e.OldValue, (T)e.NewValue );
    }

    protected virtual void OnMaximumChanged( T oldValue, T newValue )
    {
      if( this.IsInitialized )
      {
        SetValidSpinDirection();
      }
    }

    private static object OnCoerceMaximum( DependencyObject d, object baseValue )
    {
      UpDownBase<T> upDown = d as UpDownBase<T>;
      if( upDown != null )
        return upDown.OnCoerceMaximum( (T)baseValue );

      return baseValue;
    }

    protected virtual T OnCoerceMaximum( T baseValue )
    {
      return baseValue;
    }

    #endregion //Maximum

    #region Minimum

    public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register( "Minimum", typeof( T ), typeof( UpDownBase<T> ), new

UIPropertyMetadata( default( T ), OnMinimumChanged, OnCoerceMinimum ) );
    public T Minimum
    {
      get
      {
        return (T)GetValue( MinimumProperty );
      }
      set
      {
        SetValue( MinimumProperty, value );
      }
    }

    private static void OnMinimumChanged( DependencyObject o, DependencyPropertyChangedEventArgs e )
    {
      UpDownBase<T> upDown = o as UpDownBase<T>;
      if( upDown != null )
        upDown.OnMinimumChanged( (T)e.OldValue, (T)e.NewValue );
    }

    protected virtual void OnMinimumChanged( T oldValue, T newValue )
    {
      if( this.IsInitialized )
      {
        SetValidSpinDirection();
      }
    }

    private static object OnCoerceMinimum( DependencyObject d, object baseValue )
    {
      UpDownBase<T> upDown = d as UpDownBase<T>;
      if( upDown != null )
        return upDown.OnCoerceMinimum( (T)baseValue );

      return baseValue;
    }

    protected virtual T OnCoerceMinimum( T baseValue )
    {
      return baseValue;
    }

    #endregion //Minimum

    #region MouseWheelActiveTrigger

    /// <summary>
    /// Identifies the MouseWheelActiveTrigger dependency property
    /// </summary>
    public static readonly DependencyProperty MouseWheelActiveTriggerProperty = DependencyProperty.Register( "MouseWheelActiveTrigger", typeof(

MouseWheelActiveTrigger ), typeof( UpDownBase<T> ), new UIPropertyMetadata( MouseWheelActiveTrigger.FocusedMouseOver ) );

    /// <summary>
    /// Get or set when the mouse wheel event should affect the value.
    /// </summary>
    public MouseWheelActiveTrigger MouseWheelActiveTrigger
    {
      get
      {
        return (MouseWheelActiveTrigger)GetValue( MouseWheelActiveTriggerProperty );
      }
      set
      {
        SetValue( MouseWheelActiveTriggerProperty, value );
      }
    }

    #endregion //MouseWheelActiveTrigger

    #region MouseWheelActiveOnFocus

    [Obsolete( "Use MouseWheelActiveTrigger property instead" )]
    public static readonly DependencyProperty MouseWheelActiveOnFocusProperty = DependencyProperty.Register( "MouseWheelActiveOnFocus", typeof( bool

), typeof( UpDownBase<T> ), new UIPropertyMetadata( true, OnMouseWheelActiveOnFocusChanged ) );

    [Obsolete( "Use MouseWheelActiveTrigger property instead" )]
    public bool MouseWheelActiveOnFocus
    {
      get
      {
#pragma warning disable 618
        return (bool)GetValue( MouseWheelActiveOnFocusProperty );
#pragma warning restore 618
      }
      set
      {
#pragma warning disable 618
        SetValue( MouseWheelActiveOnFocusProperty, value );
#pragma warning restore 618
      }
    }

    private static void OnMouseWheelActiveOnFocusChanged( DependencyObject o, DependencyPropertyChangedEventArgs e )
    {
      UpDownBase<T> upDownBase = o as UpDownBase<T>;
      if( upDownBase != null )
        upDownBase.MouseWheelActiveTrigger = ((bool)e.NewValue)
          ? MouseWheelActiveTrigger.FocusedMouseOver
          : MouseWheelActiveTrigger.MouseOver;
    }

    #endregion //MouseWheelActiveOnFocus

    #region ShowButtonSpinner

    public static readonly DependencyProperty ShowButtonSpinnerProperty = DependencyProperty.Register( "ShowButtonSpinner", typeof( bool ), typeof(

UpDownBase<T> ), new UIPropertyMetadata( true ) );
    public bool ShowButtonSpinner
    {
      get
      {
        return (bool)GetValue( ShowButtonSpinnerProperty );
      }
      set
      {
        SetValue( ShowButtonSpinnerProperty, value );
      }
    }

    #endregion //ShowButtonSpinner

    #region UpdateValueOnEnterKey

    public static readonly DependencyProperty UpdateValueOnEnterKeyProperty = DependencyProperty.Register( "UpdateValueOnEnterKey", typeof( bool ), typeof( UpDownBase<T> ), 
      new FrameworkPropertyMetadata( false, OnUpdateValueOnEnterKeyChanged ) );
    public bool UpdateValueOnEnterKey
    {
      get
      {
        return (bool)GetValue( UpdateValueOnEnterKeyProperty );
      }
      set
      {
        SetValue( UpdateValueOnEnterKeyProperty, value );
      }
    }

    private static void OnUpdateValueOnEnterKeyChanged( DependencyObject o, DependencyPropertyChangedEventArgs e )
    {
      var upDownBase = o as UpDownBase<T>;
      if( upDownBase != null )
        upDownBase.OnUpdateValueOnEnterKeyChanged( ( bool )e.OldValue, ( bool )e.NewValue );
    }

    protected virtual void OnUpdateValueOnEnterKeyChanged( bool oldValue, bool newValue )
    {
    }

    #endregion //UpdateValueOnEnterKey

    #region Value

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof( T ), typeof( UpDownBase<T> ), 
      new FrameworkPropertyMetadata( default( T ), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged, OnCoerceValue, false, UpdateSourceTrigger.PropertyChanged ) );
    public T Value
    {
      get
      {
        return (T)GetValue( ValueProperty );
      }
      set
      {
        SetValue( ValueProperty, value );
      }
    }

    private void SetValueInternal( T value )
    {
      _internalValueSet = true;
      try
      {
        this.Value = value;
      }
      finally
      {
        _internalValueSet = false;
      }
    }

    private static object OnCoerceValue( DependencyObject o, object basevalue )
    {
      return ((UpDownBase<T>)o).OnCoerceValue( basevalue );
    }

    protected virtual object OnCoerceValue( object newValue )
    {
      return newValue;
    }

    private static void OnValueChanged( DependencyObject o, DependencyPropertyChangedEventArgs e )
    {
      UpDownBase<T> upDownBase = o as UpDownBase<T>;
      if( upDownBase != null )
        upDownBase.OnValueChanged( (T)e.OldValue, (T)e.NewValue );
    }

    protected virtual void OnValueChanged( T oldValue, T newValue )
    {
      if( !_internalValueSet && this.IsInitialized )
      {
        SyncTextAndValueProperties( false, null, true );
      }

      SetValidSpinDirection();

      this.RaiseValueChangedEvent( oldValue, newValue );
    }

    #endregion //Value

    #endregion //Properties

    #region Constructors

    internal UpDownBase()
    {

      this.AddHandler( Mouse.PreviewMouseDownOutsideCapturedElementEvent, new RoutedEventHandler( this.HandleClickOutsideOfControlWithMouseCapture ),

true );
      this.IsKeyboardFocusWithinChanged += this.UpDownBase_IsKeyboardFocusWithinChanged;
    }

    #endregion //Constructors

    #region Base Class Overrides

    protected override void OnAccessKey( AccessKeyEventArgs e )
    {
      if( TextBox != null )
        TextBox.Focus();

      base.OnAccessKey( e );
    }

    public override void OnApplyTemplate()
    {
      base.OnApplyTemplate();

      if( TextBox != null )
      {
        TextBox.TextChanged -= new TextChangedEventHandler( TextBox_TextChanged );
        TextBox.RemoveHandler( Mouse.PreviewMouseDownEvent, new MouseButtonEventHandler( this.TextBox_PreviewMouseDown ) );
      }

      TextBox = GetTemplateChild( PART_TextBox ) as TextBox;

      if( TextBox != null )
      {
        TextBox.Text = Text;
        TextBox.TextChanged += new TextChangedEventHandler( TextBox_TextChanged );
        TextBox.AddHandler( Mouse.PreviewMouseDownEvent, new MouseButtonEventHandler( this.TextBox_PreviewMouseDown ), true );
      }

      if( Spinner != null )
        Spinner.Spin -= OnSpinnerSpin;

      Spinner = GetTemplateChild( PART_Spinner ) as Spinner;

      if( Spinner != null )
        Spinner.Spin += OnSpinnerSpin;

      SetValidSpinDirection();
    }

    protected override void OnKeyDown( KeyEventArgs e )
    {
      switch( e.Key )
      {
        case Key.Enter:
          {
            // Commit Text on "Enter" to raise Error event 
            bool commitSuccess = CommitInput();
            //Only handle if an exception is detected (Commit fails)
            e.Handled = !commitSuccess;
            break;
          }
      }
    }

    protected override void OnTextChanged( string oldValue, string newValue )
    {
      if( this.IsInitialized )
      {
        // When text is typed, if UpdateValueOnEnterKey is true, 
        // Sync Value on Text only when Enter Key is pressed.
        if( this.UpdateValueOnEnterKey )
        {
          if( !_isTextChangedFromUI )
          {
            this.SyncTextAndValueProperties( true, Text );
          }
        }
        else
        {
          this.SyncTextAndValueProperties( true, Text );
        }
      }
    }

    protected override void OnCultureInfoChanged( CultureInfo oldValue, CultureInfo newValue )
    {
      if( IsInitialized )
      {
        SyncTextAndValueProperties( false, null );
      }
    }

    protected override void OnReadOnlyChanged( bool oldValue, bool newValue )
    {
      SetValidSpinDirection();
    }

    #endregion //Base Class Overrides

    #region Event Handlers

    private void TextBox_PreviewMouseDown( object sender, RoutedEventArgs e )
    {
      if( this.MouseWheelActiveTrigger == Primitives.MouseWheelActiveTrigger.Focused )
      {
        //Capture the spinner when user clicks on the control.
        if( Mouse.Captured != this.Spinner )
        {
          //Delay the capture to let the DateTimeUpDown select a new DateTime part.
          this.Dispatcher.BeginInvoke( DispatcherPriority.Input, new Action( () =>
          {
            Mouse.Capture( this.Spinner );
          }
          ) );
        }
      }
    }

    private void HandleClickOutsideOfControlWithMouseCapture( object sender, RoutedEventArgs e )
    {
      if( Mouse.Captured is Spinner )
      {
        //Release the captured spinner when user clicks away from spinner.
        this.Spinner.ReleaseMouseCapture();
      }
    }

    private void OnSpinnerSpin( object sender, SpinEventArgs e )
    {
      if( AllowSpin && !IsReadOnly )
      {
        var activeTrigger = this.MouseWheelActiveTrigger;
        bool spin = !e.UsingMouseWheel;
        spin |= (activeTrigger == MouseWheelActiveTrigger.MouseOver);
        spin |= ( (TextBox  != null) && TextBox.IsFocused && (activeTrigger == MouseWheelActiveTrigger.FocusedMouseOver));
        spin |= ( (TextBox != null) && TextBox.IsFocused && (activeTrigger == MouseWheelActiveTrigger.Focused) && (Mouse.Captured is Spinner));

        if( spin )
        {
          e.Handled = true;
          OnSpin( e );
        }
      }
    }

    #endregion //Event Handlers

    #region Events

    public event InputValidationErrorEventHandler InputValidationError;

    public event EventHandler<SpinEventArgs> Spinned;

    #region ValueChanged Event

    //Due to a bug in Visual Studio, you cannot create event handlers for generic T args in XAML, so I have to use object instead.
    public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent( "ValueChanged", RoutingStrategy.Bubble, typeof(

RoutedPropertyChangedEventHandler<object> ), typeof( UpDownBase<T> ) );
    public event RoutedPropertyChangedEventHandler<object> ValueChanged
    {
      add
      {
        AddHandler( ValueChangedEvent, value );
      }
      remove
      {
        RemoveHandler( ValueChangedEvent, value );
      }
    }

    #endregion

    #endregion //Events

    #region Methods

    protected virtual void OnSpin( SpinEventArgs e )
    {
      if( e == null )
        throw new ArgumentNullException( "e" );

      // Raise the Spinned event to user
      EventHandler<SpinEventArgs> handler = this.Spinned;
      if( handler != null )
      {
        handler( this, e );
      }

      if( e.Direction == SpinDirection.Increase )
        DoIncrement();
      else
        DoDecrement();
    }

    protected virtual void RaiseValueChangedEvent( T oldValue, T newValue )
    {
      RoutedPropertyChangedEventArgs<object> args = new RoutedPropertyChangedEventArgs<object>( oldValue, newValue );
      args.RoutedEvent = ValueChangedEvent;
      RaiseEvent( args );
    }

    protected override void OnInitialized( EventArgs e )
    {
      base.OnInitialized( e );
      // When both Value and Text are initialized, Value has priority.
      // To be sure that the value is not initialized, it should
      // have no local value, no binding, and equal to the default value.
      bool updateValueFromText =
        (this.ReadLocalValue( ValueProperty ) == DependencyProperty.UnsetValue)
        && (BindingOperations.GetBinding( this, ValueProperty ) == null)
        && (object.Equals( this.Value, ValueProperty.DefaultMetadata.DefaultValue ));

      this.SyncTextAndValueProperties( updateValueFromText, Text, !updateValueFromText );
    }

    /// <summary>
    /// Performs an increment if conditions allow it.
    /// </summary>
    internal void DoDecrement()
    {
      if( Spinner == null || (Spinner.ValidSpinDirection & ValidSpinDirections.Decrease) == ValidSpinDirections.Decrease )
      {
        OnDecrement();
      }
    }

    /// <summary>
    /// Performs a decrement if conditions allow it.
    /// </summary>
    internal void DoIncrement()
    {
      if( Spinner == null || (Spinner.ValidSpinDirection & ValidSpinDirections.Increase) == ValidSpinDirections.Increase )
      {
        OnIncrement();
      }
    }

    private void TextBox_TextChanged( object sender, TextChangedEventArgs e )
    {
      if( !this.IsKeyboardFocusWithin )
        return;

      try
      {
        _isTextChangedFromUI = true;
        Text = ((TextBox)sender).Text;
      }
      finally
      {
        _isTextChangedFromUI = false;
      }
    }

    private void UpDownBase_IsKeyboardFocusWithinChanged( object sender, DependencyPropertyChangedEventArgs e )
    {
      if( !(bool)e.NewValue )
      {
        this.CommitInput();
      }
    }

    private void RaiseInputValidationError( Exception e )
    {
      if( InputValidationError != null )
      {
        InputValidationErrorEventArgs args = new InputValidationErrorEventArgs( e );
        InputValidationError( this, args );
        if( args.ThrowException )
        {
          throw args.Exception;
        }
      }
    }

    public virtual bool CommitInput()
    {
      return this.SyncTextAndValueProperties( true, Text );
    }

    protected bool SyncTextAndValueProperties( bool updateValueFromText, string text )
    {
      return this.SyncTextAndValueProperties( updateValueFromText, text, false );
    }

    private bool SyncTextAndValueProperties( bool updateValueFromText, string text, bool forceTextUpdate )
    {
      if( _isSyncingTextAndValueProperties )
        return true;

      _isSyncingTextAndValueProperties = true;
      bool parsedTextIsValid = true;
      try
      {
        if( updateValueFromText )
        {
          if( string.IsNullOrEmpty( text ) )
          {
            // An empty input sets the value to the default value.
            this.SetValueInternal( this.DefaultValue );
          }
          else
          {
            try
            {
              T newValue = this.ConvertTextToValue( text );
              if( !object.Equals( newValue, this.Value ) )
              {
                this.SetValueInternal( newValue );
              }
            }
            catch( Exception e )
            {
              parsedTextIsValid = false;

              // From the UI, just allow any input.
              if( !_isTextChangedFromUI )
              {
                // This call may throw an exception. 
                // See RaiseInputValidationError() implementation.
                this.RaiseInputValidationError( e );
              }
            }
          }
        }

        // Do not touch the ongoing text input from user.
        if( !_isTextChangedFromUI )
        {
          // Don't replace the empty Text with the non-empty representation of DefaultValue.
          bool shouldKeepEmpty = !forceTextUpdate && string.IsNullOrEmpty( Text ) && object.Equals( Value, DefaultValue ) && !this.DisplayDefaultValueOnEmptyText;
          if( !shouldKeepEmpty )
          {
            string newText = ConvertValueToText();
            if( !object.Equals( this.Text, newText ) )
            {
              Text = newText;
            }
          }

          // Sync Text and textBox
          if( TextBox != null )
            TextBox.Text = Text;
        }

        if( _isTextChangedFromUI && !parsedTextIsValid )
        {
          // Text input was made from the user and the text
          // repesents an invalid value. Disable the spinner
          // in this case.
          if( Spinner != null )
          {
            Spinner.ValidSpinDirection = ValidSpinDirections.None;
          }
        }
        else
        {
          this.SetValidSpinDirection();
        }
      }
      finally
      {
        _isSyncingTextAndValueProperties = false;
      }
      return parsedTextIsValid;
    }

    #region Abstract

    /// <summary>
    /// Converts the formatted text to a value.
    /// </summary>
    protected abstract T ConvertTextToValue( string text );

    /// <summary>
    /// Converts the value to formatted text.
    /// </summary>
    /// <returns></returns>
    protected abstract string ConvertValueToText();

    /// <summary>
    /// Called by OnSpin when the spin direction is SpinDirection.Increase.
    /// </summary>
    protected abstract void OnIncrement();

    /// <summary>
    /// Called by OnSpin when the spin direction is SpinDirection.Descrease.
    /// </summary>
    protected abstract void OnDecrement();

    /// <summary>
    /// Sets the valid spin directions.
    /// </summary>
    protected abstract void SetValidSpinDirection();

    #endregion //Abstract

    #endregion //Methods
  }
}