diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoCompletingMaskEventArgs.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoCompletingMaskEventArgs.cs deleted file mode 100644 index da2ef737e..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoCompletingMaskEventArgs.cs +++ /dev/null @@ -1,101 +0,0 @@ -/************************************************************************************* - - 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.ComponentModel; - -namespace HandyControl.Controls; - -public class AutoCompletingMaskEventArgs : CancelEventArgs -{ -public AutoCompletingMaskEventArgs( MaskedTextProvider maskedTextProvider, int startPosition, int selectionLength, string input ) -{ - m_autoCompleteStartPosition = -1; - - m_maskedTextProvider = maskedTextProvider; - m_startPosition = startPosition; - m_selectionLength = selectionLength; - m_input = input; -} - -#region MaskedTextProvider PROPERTY - -private MaskedTextProvider m_maskedTextProvider; - -public MaskedTextProvider MaskedTextProvider -{ - get { return m_maskedTextProvider; } -} - -#endregion MaskedTextProvider PROPERTY - -#region StartPosition PROPERTY - -private int m_startPosition; - -public int StartPosition -{ - get { return m_startPosition; } -} - -#endregion StartPosition PROPERTY - -#region SelectionLength PROPERTY - -private int m_selectionLength; - -public int SelectionLength -{ - get { return m_selectionLength; } -} - -#endregion SelectionLength PROPERTY - -#region Input PROPERTY - -private string m_input; - -public string Input -{ - get { return m_input; } -} - -#endregion Input PROPERTY - - -#region AutoCompleteStartPosition PROPERTY - -private int m_autoCompleteStartPosition; - -public int AutoCompleteStartPosition -{ - get { return m_autoCompleteStartPosition; } - set { m_autoCompleteStartPosition = value; } -} - -#endregion AutoCompleteStartPosition PROPERTY - -#region AutoCompleteText PROPERTY - -private string m_autoCompleteText; - -public string AutoCompleteText -{ - get { return m_autoCompleteText; } - set { m_autoCompleteText = value; } -} - -#endregion AutoCompleteText PROPERTY -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoSelectBehavior.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoSelectBehavior.cs deleted file mode 100644 index cd0c4ab1b..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoSelectBehavior.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace HandyControl.Controls; - -public enum AutoSelectBehavior -{ - Never, - OnFocus -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoSelectTextBox.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoSelectTextBox.cs deleted file mode 100644 index ecf705acf..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/AutoSelectTextBox.cs +++ /dev/null @@ -1,281 +0,0 @@ -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; - -namespace HandyControl.Controls; - -public class AutoSelectTextBox : TextBox -{ - public AutoSelectTextBox() - { - } - - #region AutoSelectBehavior PROPERTY - - - public AutoSelectBehavior AutoSelectBehavior - { - get - { - return (AutoSelectBehavior)GetValue(AutoSelectBehaviorProperty); - } - set - { - SetValue(AutoSelectBehaviorProperty, value); - } - } - - public static readonly DependencyProperty AutoSelectBehaviorProperty = - DependencyProperty.Register("AutoSelectBehavior", typeof(AutoSelectBehavior), typeof(AutoSelectTextBox), - new UIPropertyMetadata(AutoSelectBehavior.Never)); - - #endregion AutoSelectBehavior PROPERTY - - #region AutoMoveFocus PROPERTY - - public bool AutoMoveFocus - { - get - { - return (bool)GetValue(AutoMoveFocusProperty); - } - set - { - SetValue(AutoMoveFocusProperty, value); - } - } - - public static readonly DependencyProperty AutoMoveFocusProperty = - DependencyProperty.Register("AutoMoveFocus", typeof(bool), typeof(AutoSelectTextBox), new UIPropertyMetadata(false)); - - #endregion AutoMoveFocus PROPERTY - - #region QueryMoveFocus EVENT - - public static readonly RoutedEvent QueryMoveFocusEvent = EventManager.RegisterRoutedEvent("QueryMoveFocus", - RoutingStrategy.Bubble, - typeof(QueryMoveFocusEventHandler), - typeof(AutoSelectTextBox)); - #endregion QueryMoveFocus EVENT - - protected override void OnPreviewKeyDown(KeyEventArgs e) - { - if (!this.AutoMoveFocus) - { - base.OnPreviewKeyDown(e); - return; - } - - if ((e.Key == Key.Left) - && ((Keyboard.Modifiers == ModifierKeys.None) - || (Keyboard.Modifiers == ModifierKeys.Control))) - { - e.Handled = this.MoveFocusLeft(); - } - - if ((e.Key == Key.Right) - && ((Keyboard.Modifiers == ModifierKeys.None) - || (Keyboard.Modifiers == ModifierKeys.Control))) - { - e.Handled = this.MoveFocusRight(); - } - - if (((e.Key == Key.Up) || (e.Key == Key.PageUp)) - && ((Keyboard.Modifiers == ModifierKeys.None) - || (Keyboard.Modifiers == ModifierKeys.Control))) - { - e.Handled = this.MoveFocusUp(); - } - - if (((e.Key == Key.Down) || (e.Key == Key.PageDown)) - && ((Keyboard.Modifiers == ModifierKeys.None) - || (Keyboard.Modifiers == ModifierKeys.Control))) - { - e.Handled = this.MoveFocusDown(); - } - - base.OnPreviewKeyDown(e); - } - - protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e) - { - base.OnPreviewGotKeyboardFocus(e); - - if (this.AutoSelectBehavior == AutoSelectBehavior.OnFocus) - { - // If the focus was not in one of our child ( or popup ), we select all the text. - if (!TreeHelper.IsDescendantOf(e.OldFocus as DependencyObject, this)) - { - this.SelectAll(); - } - } - } - - protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e) - { - base.OnPreviewMouseLeftButtonDown(e); - - if (this.AutoSelectBehavior == AutoSelectBehavior.Never) - return; - - if (this.IsKeyboardFocusWithin == false) - { - this.Focus(); - e.Handled = true; //prevent from removing the selection - } - } - - protected override void OnTextChanged(TextChangedEventArgs e) - { - base.OnTextChanged(e); - - if (!this.AutoMoveFocus) - return; - - if ((this.Text.Length != 0) - && (this.Text.Length == this.MaxLength) - && (this.CaretIndex == this.MaxLength)) - { - if (this.CanMoveFocus(FocusNavigationDirection.Right, true) == true) - { - FocusNavigationDirection direction = (this.FlowDirection == FlowDirection.LeftToRight) - ? FocusNavigationDirection.Right - : FocusNavigationDirection.Left; - - this.MoveFocus(new TraversalRequest(direction)); - } - } - } - - - private bool CanMoveFocus(FocusNavigationDirection direction, bool reachedMax) - { - QueryMoveFocusEventArgs e = new QueryMoveFocusEventArgs(direction, reachedMax); - this.RaiseEvent(e); - return e.CanMoveFocus; - } - - private bool MoveFocusLeft() - { - if (this.FlowDirection == FlowDirection.LeftToRight) - { - //occurs only if the cursor is at the beginning of the text - if ((this.CaretIndex == 0) && (this.SelectionLength == 0)) - { - if (ComponentCommands.MoveFocusBack.CanExecute(null, this)) - { - ComponentCommands.MoveFocusBack.Execute(null, this); - return true; - } - else if (this.CanMoveFocus(FocusNavigationDirection.Left, false)) - { - this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Left)); - return true; - } - } - } - else - { - //occurs only if the cursor is at the end of the text - if ((this.CaretIndex == this.Text.Length) && (this.SelectionLength == 0)) - { - if (ComponentCommands.MoveFocusBack.CanExecute(null, this)) - { - ComponentCommands.MoveFocusBack.Execute(null, this); - return true; - } - else if (this.CanMoveFocus(FocusNavigationDirection.Left, false)) - { - this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Left)); - return true; - } - } - } - - return false; - } - - private bool MoveFocusRight() - { - if (this.FlowDirection == FlowDirection.LeftToRight) - { - //occurs only if the cursor is at the beginning of the text - if ((this.CaretIndex == this.Text.Length) && (this.SelectionLength == 0)) - { - if (ComponentCommands.MoveFocusForward.CanExecute(null, this)) - { - ComponentCommands.MoveFocusForward.Execute(null, this); - return true; - } - else if (this.CanMoveFocus(FocusNavigationDirection.Right, false)) - { - this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right)); - return true; - } - } - } - else - { - //occurs only if the cursor is at the end of the text - if ((this.CaretIndex == 0) && (this.SelectionLength == 0)) - { - if (ComponentCommands.MoveFocusForward.CanExecute(null, this)) - { - ComponentCommands.MoveFocusForward.Execute(null, this); - return true; - } - else if (this.CanMoveFocus(FocusNavigationDirection.Right, false)) - { - this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right)); - return true; - } - } - } - - return false; - } - - private bool MoveFocusUp() - { - int lineNumber = this.GetLineIndexFromCharacterIndex(this.SelectionStart); - - //occurs only if the cursor is on the first line - if (lineNumber == 0) - { - if (ComponentCommands.MoveFocusUp.CanExecute(null, this)) - { - ComponentCommands.MoveFocusUp.Execute(null, this); - return true; - } - else if (this.CanMoveFocus(FocusNavigationDirection.Up, false)) - { - this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Up)); - return true; - } - } - - return false; - } - - private bool MoveFocusDown() - { - int lineNumber = this.GetLineIndexFromCharacterIndex(this.SelectionStart); - - //occurs only if the cursor is on the first line - if (lineNumber == (this.LineCount - 1)) - { - if (ComponentCommands.MoveFocusDown.CanExecute(null, this)) - { - ComponentCommands.MoveFocusDown.Execute(null, this); - return true; - } - else if (this.CanMoveFocus(FocusNavigationDirection.Down, false)) - { - this.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down)); - return true; - } - } - - return false; - } -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/CachedTextInfo.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/CachedTextInfo.cs deleted file mode 100644 index 84e141000..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/CachedTextInfo.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; - -namespace HandyControl.Controls; - -internal class CachedTextInfo : ICloneable -{ - private CachedTextInfo(string text, int caretIndex, int selectionStart, int selectionLength) - { - this.Text = text; - this.CaretIndex = caretIndex; - this.SelectionStart = selectionStart; - this.SelectionLength = selectionLength; - } - - public CachedTextInfo(TextBox textBox) - : this(textBox.Text, textBox.CaretIndex, textBox.SelectionStart, textBox.SelectionLength) - { - } - - public string Text { get; private set; } - public int CaretIndex { get; private set; } - public int SelectionStart { get; private set; } - public int SelectionLength { get; private set; } - - #region ICloneable Members - - public object Clone() - { - return new CachedTextInfo(this.Text, this.CaretIndex, this.SelectionStart, this.SelectionLength); - } - - #endregion -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/ChangeTypeHelper.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/ChangeTypeHelper.cs deleted file mode 100644 index 876478fb8..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/ChangeTypeHelper.cs +++ /dev/null @@ -1,34 +0,0 @@ -using System; -using System.ComponentModel; - -namespace HandyControl.Controls; - -internal static class ChangeTypeHelper -{ - internal static object ChangeType(object value, Type conversionType, IFormatProvider provider) - { - if (conversionType == null) - { - throw new ArgumentNullException("conversionType"); - } - if (conversionType == typeof(Guid)) - { - return new Guid(value.ToString()); - } - else if (conversionType == typeof(Guid?)) - { - if (value == null) - return null; - return new Guid(value.ToString()); - } - else if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) - { - if (value == null) - return null; - NullableConverter nullableConverter = new NullableConverter(conversionType); - conversionType = nullableConverter.UnderlyingType; - } - - return System.Convert.ChangeType(value, conversionType, provider); - } -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/InsertKeyModeEnum.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/InsertKeyModeEnum.cs deleted file mode 100644 index d81fc45e5..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/InsertKeyModeEnum.cs +++ /dev/null @@ -1,24 +0,0 @@ -/************************************************************************************* - - 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 - - ***********************************************************************************/ - -namespace HandyControl.Controls; - -public enum InsertKeyMode -{ -Default = 0, -Insert = 1, -Overwrite = 2 -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/MaskFormatEnum.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/MaskFormatEnum.cs deleted file mode 100644 index e7ee72022..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/MaskFormatEnum.cs +++ /dev/null @@ -1,25 +0,0 @@ -/************************************************************************************* - - 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 - - ***********************************************************************************/ - -namespace HandyControl.Controls; - -public enum MaskFormat -{ -ExcludePromptAndLiterals, -IncludeLiterals, -IncludePrompt, -IncludePromptAndLiterals -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/MaskedTextBox.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/MaskedTextBox.cs deleted file mode 100644 index 41208e599..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/MaskedTextBox.cs +++ /dev/null @@ -1,1946 +0,0 @@ -/************************************************************************************* - - 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.Collections.Generic; -using System.Text; -using System.Windows.Controls; -using System.Windows; -using System.ComponentModel; -using System.Windows.Input; -using System.Diagnostics; -using System.Windows.Documents; -using System.Globalization; -using System.Reflection; - -using System.Security; -using System.Security.Permissions; - -namespace HandyControl.Controls; - -public class MaskedTextBox : ValueRangeTextBox -{ -#region STATIC MEMBERS - -private static readonly char[] MaskChars = { '0', '9', '#', 'L', '?', '&', 'C', 'A', 'a', '.', ',', ':', '/', '$', '<', '>', '|', '\\' }; - -private static char DefaultPasswordChar = '\0'; - -private static string NullMaskString = "<>"; - -private static string GetRawText( MaskedTextProvider provider ) -{ - return provider.ToString( true, false, false, 0, provider.Length ); -} - -public static string GetFormatSpecifierFromMask( string mask, IFormatProvider formatProvider ) -{ - List notUsed; - - return MaskedTextBox.GetFormatSpecifierFromMask( - mask, - MaskedTextBox.MaskChars, - formatProvider, - true, - out notUsed ); -} - -private static string GetFormatSpecifierFromMask( - string mask, - char[] maskChars, - IFormatProvider formatProvider, - bool includeNonSeparatorLiteralsInValue, - out List unhandledLiteralsPositions ) -{ - unhandledLiteralsPositions = new List(); - - NumberFormatInfo numberFormatInfo = NumberFormatInfo.GetInstance( formatProvider ); - - StringBuilder formatSpecifierBuilder = new StringBuilder( 32 ); - - // Space will be considered as a separator literals and will be included - // no matter the value of IncludeNonSeparatorLiteralsInValue. - bool lastCharIsLiteralIdentifier = false; - int i = 0; - int j = 0; - - while( i < mask.Length ) - { - char currentChar = mask[ i ]; - - if( ( currentChar == '\\' ) && ( !lastCharIsLiteralIdentifier ) ) - { - lastCharIsLiteralIdentifier = true; - } - else - { - if( ( lastCharIsLiteralIdentifier ) || ( Array.IndexOf( maskChars, currentChar ) < 0 ) ) - { - lastCharIsLiteralIdentifier = false; - - // The currentChar was preceeded by a liteal identifier or is not part of the MaskedTextProvider mask chars. - formatSpecifierBuilder.Append( '\\' ); - formatSpecifierBuilder.Append( currentChar ); - - if( ( !includeNonSeparatorLiteralsInValue ) && ( currentChar != ' ' ) ) - unhandledLiteralsPositions.Add( j ); - - j++; - } - else - { - // The currentChar is part of the MaskedTextProvider mask chars. - if( ( currentChar == '0' ) || ( currentChar == '9' ) || ( currentChar == '#' ) ) - { - formatSpecifierBuilder.Append( '0' ); - j++; - } - else if( currentChar == '.' ) - { - formatSpecifierBuilder.Append( '.' ); - j += numberFormatInfo.NumberDecimalSeparator.Length; - } - else if( currentChar == ',' ) - { - formatSpecifierBuilder.Append( ',' ); - j += numberFormatInfo.NumberGroupSeparator.Length; - } - else if( currentChar == '$' ) - { - string currencySymbol = numberFormatInfo.CurrencySymbol; - - formatSpecifierBuilder.Append( '"' ); - formatSpecifierBuilder.Append( currencySymbol ); - formatSpecifierBuilder.Append( '"' ); - - for( int k = 0; k < currencySymbol.Length; k++ ) - { - if( !includeNonSeparatorLiteralsInValue ) - unhandledLiteralsPositions.Add( j ); - - j++; - } - } - else - { - formatSpecifierBuilder.Append( currentChar ); - - if( ( !includeNonSeparatorLiteralsInValue ) && ( currentChar != ' ' ) ) - unhandledLiteralsPositions.Add( j ); - - j++; - } - } - } - - i++; - } - - return formatSpecifierBuilder.ToString(); -} - -#endregion STATIC MEMBERS - -#region CONSTRUCTORS - -static MaskedTextBox() -{ - MaskedTextBox.TextProperty.OverrideMetadata( typeof( MaskedTextBox ), - new FrameworkPropertyMetadata( - null, - new CoerceValueCallback( MaskedTextBox.TextCoerceValueCallback ) ) ); -} - -public MaskedTextBox() -{ - CommandManager.AddPreviewCanExecuteHandler( this, new CanExecuteRoutedEventHandler( this.OnPreviewCanExecuteCommands ) ); - CommandManager.AddPreviewExecutedHandler( this, new ExecutedRoutedEventHandler( this.OnPreviewExecutedCommands ) ); - - this.CommandBindings.Add( new CommandBinding( ApplicationCommands.Paste, null, new CanExecuteRoutedEventHandler( this.CanExecutePaste ) ) ); - this.CommandBindings.Add( new CommandBinding( ApplicationCommands.Cut, null, new CanExecuteRoutedEventHandler( this.CanExecuteCut ) ) ); - this.CommandBindings.Add( new CommandBinding( ApplicationCommands.Copy, null, new CanExecuteRoutedEventHandler( this.CanExecuteCopy ) ) ); - this.CommandBindings.Add( new CommandBinding( EditingCommands.ToggleInsert, new ExecutedRoutedEventHandler( this.ToggleInsertExecutedCallback ) ) ); - - this.CommandBindings.Add( new CommandBinding( EditingCommands.Delete, null, new CanExecuteRoutedEventHandler( this.CanExecuteDelete ) ) ); - this.CommandBindings.Add( new CommandBinding( EditingCommands.DeletePreviousWord, null, new CanExecuteRoutedEventHandler( this.CanExecuteDeletePreviousWord ) ) ); - this.CommandBindings.Add( new CommandBinding( EditingCommands.DeleteNextWord, null, new CanExecuteRoutedEventHandler( this.CanExecuteDeleteNextWord ) ) ); - - this.CommandBindings.Add( new CommandBinding( EditingCommands.Backspace, null, new CanExecuteRoutedEventHandler( this.CanExecuteBackspace ) ) ); - - System.Windows.DragDrop.AddPreviewQueryContinueDragHandler( this, new QueryContinueDragEventHandler( this.PreviewQueryContinueDragCallback ) ); - this.AllowDrop = false; -} - -[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1820:TestForEmptyStringsUsingStringLength" )] -private void InitializeMaskedTextProvider() -{ - string preInitializedText = this.Text; - - string mask = this.Mask; - - if( mask == string.Empty ) - { - m_maskedTextProvider = this.CreateMaskedTextProvider( MaskedTextBox.NullMaskString ); - m_maskIsNull = true; - } - else - { - m_maskedTextProvider = this.CreateMaskedTextProvider( mask ); - m_maskIsNull = false; - } - - if( ( !m_maskIsNull ) && ( preInitializedText != string.Empty ) ) - { - bool success = m_maskedTextProvider.Add( preInitializedText ); - - if( ( !success ) && ( !DesignerProperties.GetIsInDesignMode( this ) ) ) - throw new InvalidOperationException( "An attempt was made to apply a new mask that cannot be applied to the current text." ); - } -} - -#endregion CONSTRUCTORS - -#region ISupportInitialize - -protected override void OnInitialized( EventArgs e ) -{ - this.InitializeMaskedTextProvider(); - - this.SetIsMaskCompleted( m_maskedTextProvider.MaskCompleted ); - this.SetIsMaskFull( m_maskedTextProvider.MaskFull ); - - base.OnInitialized( e ); -} - -#endregion ISupportInitialize - -#region AllowPromptAsInput Property - -public static readonly DependencyProperty AllowPromptAsInputProperty = - DependencyProperty.Register( "AllowPromptAsInput", typeof( bool ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - true, - new PropertyChangedCallback( MaskedTextBox.AllowPromptAsInputPropertyChangedCallback ) ) ); - -public bool AllowPromptAsInput -{ - get - { - return ( bool )GetValue( AllowPromptAsInputProperty ); - } - set - { - SetValue( AllowPromptAsInputProperty, value ); - } -} - -private static void AllowPromptAsInputPropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - if( maskedTextBox.m_maskIsNull ) - return; - - maskedTextBox.m_maskedTextProvider = maskedTextBox.CreateMaskedTextProvider( maskedTextBox.Mask ); -} - -#endregion AllowPromptAsInput Property - -#region ClipboardMaskFormat Property - -public MaskFormat ClipboardMaskFormat -{ - get - { - return ( MaskFormat )GetValue( ClipboardMaskFormatProperty ); - } - set - { - SetValue( ClipboardMaskFormatProperty, value ); - } -} - -public static readonly DependencyProperty ClipboardMaskFormatProperty = - DependencyProperty.Register( "ClipboardMaskFormat", typeof( MaskFormat ), typeof( MaskedTextBox ), - new UIPropertyMetadata( MaskFormat.IncludeLiterals ) ); - -#endregion ClipboardMaskFormat Property - -#region HidePromptOnLeave Property - -public bool HidePromptOnLeave -{ - get - { - return ( bool )GetValue( HidePromptOnLeaveProperty ); - } - set - { - SetValue( HidePromptOnLeaveProperty, value ); - } -} - -public static readonly DependencyProperty HidePromptOnLeaveProperty = - DependencyProperty.Register( "HidePromptOnLeave", typeof( bool ), typeof( MaskedTextBox ), new UIPropertyMetadata( false ) ); - -#endregion HidePromptOnLeave Property - -#region IncludeLiteralsInValue Property - -public bool IncludeLiteralsInValue -{ - get - { - return ( bool )GetValue( IncludeLiteralsInValueProperty ); - } - set - { - SetValue( IncludeLiteralsInValueProperty, value ); - } -} - -public static readonly DependencyProperty IncludeLiteralsInValueProperty = - DependencyProperty.Register( "IncludeLiteralsInValue", typeof( bool ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - true, - new PropertyChangedCallback( MaskedTextBox.InlcudeLiteralsInValuePropertyChangedCallback ) ) ); - -private static void InlcudeLiteralsInValuePropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - maskedTextBox.RefreshConversionHelpers(); - maskedTextBox.RefreshValue(); -} - -#endregion IncludeLiteralsInValue Property - -#region IncludePromptInValue Property - -public bool IncludePromptInValue -{ - get - { - return ( bool )GetValue( IncludePromptInValueProperty ); - } - set - { - SetValue( IncludePromptInValueProperty, value ); - } -} - -public static readonly DependencyProperty IncludePromptInValueProperty = - DependencyProperty.Register( "IncludePromptInValue", typeof( bool ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - false, - new PropertyChangedCallback( MaskedTextBox.IncludePromptInValuePropertyChangedCallback ) ) ); - -private static void IncludePromptInValuePropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - maskedTextBox.RefreshValue(); -} - -#endregion IncludePromptInValue Property - -#region InsertKeyMode Property - -public InsertKeyMode InsertKeyMode -{ - get - { - return ( InsertKeyMode )GetValue( InsertKeyModeProperty ); - } - set - { - SetValue( InsertKeyModeProperty, value ); - } -} - -public static readonly DependencyProperty InsertKeyModeProperty = - DependencyProperty.Register( "InsertKeyMode", typeof( InsertKeyMode ), typeof( MaskedTextBox ), new UIPropertyMetadata( InsertKeyMode.Default ) ); - -#endregion InsertKeyMode Property - -#region IsMaskCompleted Read-Only Property - -private static readonly DependencyPropertyKey IsMaskCompletedPropertyKey = - DependencyProperty.RegisterReadOnly( "IsMaskCompleted", typeof( bool ), typeof( MaskedTextBox ), new PropertyMetadata( false ) ); - -public static readonly DependencyProperty IsMaskCompletedProperty = MaskedTextBox.IsMaskCompletedPropertyKey.DependencyProperty; - - -public bool IsMaskCompleted -{ - get - { - return ( bool )this.GetValue( MaskedTextBox.IsMaskCompletedProperty ); - } -} - -private void SetIsMaskCompleted( bool value ) -{ - this.SetValue( MaskedTextBox.IsMaskCompletedPropertyKey, value ); -} - -#endregion IsMaskCompleted Read-Only Property - -#region IsMaskFull Read-Only Property - -private static readonly DependencyPropertyKey IsMaskFullPropertyKey = - DependencyProperty.RegisterReadOnly( "IsMaskFull", typeof( bool ), typeof( MaskedTextBox ), new PropertyMetadata( false ) ); - -public static readonly DependencyProperty IsMaskFullProperty = MaskedTextBox.IsMaskFullPropertyKey.DependencyProperty; - -public bool IsMaskFull -{ - get - { - return ( bool )this.GetValue( MaskedTextBox.IsMaskFullProperty ); - } -} - -private void SetIsMaskFull( bool value ) -{ - this.SetValue( MaskedTextBox.IsMaskFullPropertyKey, value ); -} - -#endregion IsMaskFull Read-Only Property - -#region Mask Property - -public static readonly DependencyProperty MaskProperty = - DependencyProperty.Register( "Mask", typeof( string ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - string.Empty, - new PropertyChangedCallback( MaskedTextBox.MaskPropertyChangedCallback ), - new CoerceValueCallback( MaskedTextBox.MaskCoerceValueCallback ) ) ); - -public string Mask -{ - get - { - return ( string )this.GetValue( MaskedTextBox.MaskProperty ); - } - set - { - this.SetValue( MaskedTextBox.MaskProperty, value ); - } -} - -[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly" )] -private static object MaskCoerceValueCallback( DependencyObject sender, object value ) -{ - if( value == null ) - value = string.Empty; - - if( value.Equals( string.Empty ) ) - return value; - - // Validate the text against the would be new Mask. - - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return value; - - bool valid; - - try - { - MaskedTextProvider provider = maskedTextBox.CreateMaskedTextProvider( ( string )value ); - - string rawText = MaskedTextBox.GetRawText( maskedTextBox.m_maskedTextProvider ); - - valid = provider.VerifyString( rawText ); - } - catch( Exception exception ) - { - throw new InvalidOperationException( "An error occured while testing the current text against the new mask.", exception ); - } - - if( !valid ) - throw new ArgumentException( "The mask cannot be applied to the current text.", "Mask" ); - - return value; -} - -[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Performance", "CA1820:TestForEmptyStringsUsingStringLength" )] -private static void MaskPropertyChangedCallback( DependencyObject sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - MaskedTextProvider provider = null; - - string mask = ( string )e.NewValue; - - if( mask == string.Empty ) - { - provider = maskedTextBox.CreateMaskedTextProvider( MaskedTextBox.NullMaskString ); - maskedTextBox.m_maskIsNull = true; - maskedTextBox.Text = ""; - } - else - { - provider = maskedTextBox.CreateMaskedTextProvider( mask ); - maskedTextBox.m_maskIsNull = false; - } - - maskedTextBox.m_maskedTextProvider = provider; - - maskedTextBox.RefreshConversionHelpers(); - - if( maskedTextBox.ValueDataType != null ) - { - string textFromValue = maskedTextBox.GetTextFromValue( maskedTextBox.Value ); - maskedTextBox.m_maskedTextProvider.Set( textFromValue ); - } - - maskedTextBox.RefreshCurrentText( true ); -} - -#endregion Mask Property - -#region MaskedTextProvider Property - -public MaskedTextProvider MaskedTextProvider -{ - get - { - if( !m_maskIsNull ) - return m_maskedTextProvider.Clone() as MaskedTextProvider; - - return null; - } -} - -#endregion MaskedTextProvider Property - -#region PromptChar Property - -public static readonly DependencyProperty PromptCharProperty = - DependencyProperty.Register( "PromptChar", typeof( char ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - '_', - new PropertyChangedCallback( MaskedTextBox.PromptCharPropertyChangedCallback ), - new CoerceValueCallback( MaskedTextBox.PromptCharCoerceValueCallback ) ) ); - -public char PromptChar -{ - get - { - return ( char )this.GetValue( MaskedTextBox.PromptCharProperty ); - } - set - { - this.SetValue( MaskedTextBox.PromptCharProperty, value ); - } -} - -private static object PromptCharCoerceValueCallback( object sender, object value ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return value; - - MaskedTextProvider provider = maskedTextBox.m_maskedTextProvider.Clone() as MaskedTextProvider; - - try - { - provider.PromptChar = ( char )value; - } - catch( Exception exception ) - { - throw new ArgumentException( "The prompt character is invalid.", exception ); - } - - return value; -} - -private static void PromptCharPropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - if( maskedTextBox.m_maskIsNull ) - return; - - maskedTextBox.m_maskedTextProvider.PromptChar = ( char )e.NewValue; - - maskedTextBox.RefreshCurrentText( true ); -} - -#endregion PromptChar Property - -#region RejectInputOnFirstFailure Property - -public bool RejectInputOnFirstFailure -{ - get - { - return ( bool )GetValue( RejectInputOnFirstFailureProperty ); - } - set - { - SetValue( RejectInputOnFirstFailureProperty, value ); - } -} - -public static readonly DependencyProperty RejectInputOnFirstFailureProperty = - DependencyProperty.Register( "RejectInputOnFirstFailure", typeof( bool ), typeof( MaskedTextBox ), new UIPropertyMetadata( true ) ); - -#endregion RejectInputOnFirstFailure Property - -#region ResetOnPrompt Property - -public bool ResetOnPrompt -{ - get - { - return ( bool )GetValue( ResetOnPromptProperty ); - } - set - { - SetValue( ResetOnPromptProperty, value ); - } -} - -public static readonly DependencyProperty ResetOnPromptProperty = - DependencyProperty.Register( "ResetOnPrompt", typeof( bool ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - true, - new PropertyChangedCallback( MaskedTextBox.ResetOnPromptPropertyChangedCallback ) ) ); - -private static void ResetOnPromptPropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - if( maskedTextBox.m_maskIsNull ) - return; - - maskedTextBox.m_maskedTextProvider.ResetOnPrompt = ( bool )e.NewValue; -} - -#endregion ResetOnPrompt Property - -#region ResetOnSpace Property - -public bool ResetOnSpace -{ - get - { - return ( bool )GetValue( ResetOnSpaceProperty ); - } - set - { - SetValue( ResetOnSpaceProperty, value ); - } -} - -public static readonly DependencyProperty ResetOnSpaceProperty = - DependencyProperty.Register( "ResetOnSpace", typeof( bool ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - true, - new PropertyChangedCallback( MaskedTextBox.ResetOnSpacePropertyChangedCallback ) ) ); - -private static void ResetOnSpacePropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - if( maskedTextBox.m_maskIsNull ) - return; - - maskedTextBox.m_maskedTextProvider.ResetOnSpace = ( bool )e.NewValue; -} - -#endregion ResetOnSpace Property - -#region RestrictToAscii Property - -public bool RestrictToAscii -{ - get - { - return ( bool )GetValue( RestrictToAsciiProperty ); - } - set - { - SetValue( RestrictToAsciiProperty, value ); - } -} - -public static readonly DependencyProperty RestrictToAsciiProperty = - DependencyProperty.Register( "RestrictToAscii", typeof( bool ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - false, - new PropertyChangedCallback( MaskedTextBox.RestrictToAsciiPropertyChangedCallback ), - new CoerceValueCallback( MaskedTextBox.RestrictToAsciiCoerceValueCallback ) ) ); - -[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly" )] -private static object RestrictToAsciiCoerceValueCallback( object sender, object value ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return value; - - if( maskedTextBox.m_maskIsNull ) - return value; - - bool restrictToAscii = ( bool )value; - - if( !restrictToAscii ) - return value; - - // Validate the text to make sure that it is only made of Ascii characters. - - MaskedTextProvider provider = maskedTextBox.CreateMaskedTextProvider( - maskedTextBox.Mask, - maskedTextBox.GetCultureInfo(), - maskedTextBox.AllowPromptAsInput, - maskedTextBox.PromptChar, - MaskedTextBox.DefaultPasswordChar, - restrictToAscii ); - - if( !provider.VerifyString( maskedTextBox.Text ) ) - throw new ArgumentException( "The current text cannot be restricted to ASCII characters. The RestrictToAscii property is set to true.", "RestrictToAscii" ); - - return restrictToAscii; -} - -private static void RestrictToAsciiPropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - if( maskedTextBox.m_maskIsNull ) - return; - - maskedTextBox.m_maskedTextProvider = maskedTextBox.CreateMaskedTextProvider( maskedTextBox.Mask ); - - maskedTextBox.RefreshCurrentText( true ); -} - -#endregion RestrictToAscii Property - -#region SkipLiterals Property - -public bool SkipLiterals -{ - get - { - return ( bool )GetValue( SkipLiteralsProperty ); - } - set - { - SetValue( SkipLiteralsProperty, value ); - } -} - -public static readonly DependencyProperty SkipLiteralsProperty = - DependencyProperty.Register( "SkipLiterals", typeof( bool ), typeof( MaskedTextBox ), - new UIPropertyMetadata( - true, - new PropertyChangedCallback( MaskedTextBox.SkipLiteralsPropertyChangedCallback ) ) ); - -private static void SkipLiteralsPropertyChangedCallback( object sender, DependencyPropertyChangedEventArgs e ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return; - - if( maskedTextBox.m_maskIsNull ) - return; - - maskedTextBox.m_maskedTextProvider.SkipLiterals = ( bool )e.NewValue; -} - -#endregion SkipLiterals Property - -#region Text Property - -private static object TextCoerceValueCallback( DependencyObject sender, object value ) -{ - MaskedTextBox maskedTextBox = sender as MaskedTextBox; - - if( !maskedTextBox.IsInitialized ) - return DependencyProperty.UnsetValue; - - if( maskedTextBox.IsInIMEComposition ) - { - // In IME Composition. We must return an uncoerced value or else the IME decorator won't disappear after text input. - return value; - } - - if( value == null ) - value = string.Empty; - - if( ( maskedTextBox.IsForcingText ) || ( maskedTextBox.m_maskIsNull ) ) - return value; - - // Only direct affectation to the Text property or binding of the Text property should - // come through here. All other cases should pre-validate the text and affect it through the ForceText method. - string text = maskedTextBox.ValidateText( ( string )value ); - - return text; -} - -private string ValidateText( string text ) -{ - string coercedText = text; - - if( this.RejectInputOnFirstFailure ) - { - MaskedTextProvider provider = m_maskedTextProvider.Clone() as MaskedTextProvider; - - int notUsed; - MaskedTextResultHint hint; - - //0 – Digit zero to 9[ Required ] - //9 – Digit 0 – 9[ Optional ] - //A – Alpha Numeric. [Required] - //a – Alpha Numeric. [Optional] - //L – Letters a-z, A-Z[ Required ] - //? – Letters a-z, A-Z[ Optional ] - //C – Any non-control character [Optional] - //< - When first, all following characters are in lower case. - //> - When first, all following characters are in upper case. - if( provider.Set( text, out notUsed, out hint ) || provider.Mask.StartsWith( ">" ) || provider.Mask.StartsWith( "<" ) ) - { - coercedText = this.GetFormattedString( provider, text ); - } - else - { - // Coerce the text to remain the same. - coercedText = this.GetFormattedString( m_maskedTextProvider, text ); - - // The TextPropertyChangedCallback won't be called. - // Therefore, we must sync the maskedTextProvider. - m_maskedTextProvider.Set( coercedText ); - } - } - else - { - MaskedTextProvider provider = ( MaskedTextProvider )m_maskedTextProvider.Clone(); - - int caretIndex; - - if( this.CanReplace( provider, text, 0, m_maskedTextProvider.Length, this.RejectInputOnFirstFailure, out caretIndex ) ) - { - coercedText = this.GetFormattedString( provider, text ); - } - else - { - // Coerce the text to remain the same. - coercedText = this.GetFormattedString( m_maskedTextProvider, text ); - - // The TextPropertyChangedCallback won't be called. - // Therefore, we must sync the maskedTextProvider. - m_maskedTextProvider.Set( coercedText ); - } - } - - return coercedText; -} - -protected override void OnTextChanged( TextChangedEventArgs e ) -{ - if( !m_maskIsNull ) - { - if( ( this.IsInValueChanged ) || ( !this.IsForcingText ) ) - { - string newText = this.Text; - - if( m_maskIsNull ) - { - this.CaretIndex = newText.Length; - } - else - { - m_maskedTextProvider.Set( newText ); - - if( m_maskedTextProvider.Mask.StartsWith( ">" ) || m_maskedTextProvider.Mask.StartsWith( "<" ) ) - { - this.CaretIndex = newText.Length; - } - else - { - int caretIndex = m_maskedTextProvider.FindUnassignedEditPositionFrom( 0, true ); - - if( caretIndex == -1 ) - caretIndex = m_maskedTextProvider.Length; - - this.CaretIndex = caretIndex; - } - } - } - } - - // m_maskedTextProvider can be null in the designer. With WPF 3.5 SP1, sometimes, - // TextChanged will be triggered before OnInitialized is called. - if( m_maskedTextProvider != null ) - { - this.SetIsMaskCompleted( m_maskedTextProvider.MaskCompleted ); - this.SetIsMaskFull( m_maskedTextProvider.MaskFull ); - } - - base.OnTextChanged( e ); -} - -#endregion Text Property - - -#region COMMANDS - -private void OnPreviewCanExecuteCommands( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - RoutedUICommand routedUICommand = e.Command as RoutedUICommand; - - if( ( routedUICommand != null ) - && ( ( routedUICommand.Name == "Space" ) || ( routedUICommand.Name == "ShiftSpace" ) ) ) - { - if( this.IsReadOnly ) - { - e.CanExecute = false; - } - else - { - MaskedTextProvider provider = ( MaskedTextProvider )m_maskedTextProvider.Clone(); - int caretIndex; - e.CanExecute = this.CanReplace( provider, " ", this.SelectionStart, this.SelectionLength, this.RejectInputOnFirstFailure, out caretIndex ); - } - - e.Handled = true; - } - else if( ( e.Command == ApplicationCommands.Undo ) || ( e.Command == ApplicationCommands.Redo ) ) - { - e.CanExecute = false; - e.Handled = true; - } -} - -private void OnPreviewExecutedCommands( object sender, ExecutedRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - if( e.Command == EditingCommands.Delete ) - { - e.Handled = true; - this.Delete( this.SelectionStart, this.SelectionLength, true ); - } - else if( e.Command == EditingCommands.DeleteNextWord ) - { - e.Handled = true; - EditingCommands.SelectRightByWord.Execute( null, this as IInputElement ); - this.Delete( this.SelectionStart, this.SelectionLength, true ); - } - else if( e.Command == EditingCommands.DeletePreviousWord ) - { - e.Handled = true; - EditingCommands.SelectLeftByWord.Execute( null, this as IInputElement ); - this.Delete( this.SelectionStart, this.SelectionLength, false ); - } - else if( e.Command == EditingCommands.Backspace ) - { - e.Handled = true; - this.Delete( this.SelectionStart, this.SelectionLength, false ); - } - else if( e.Command == ApplicationCommands.Cut ) - { - e.Handled = true; - - if( ApplicationCommands.Copy.CanExecute( null, this as IInputElement ) ) - ApplicationCommands.Copy.Execute( null, this as IInputElement ); - - this.Delete( this.SelectionStart, this.SelectionLength, true ); - } - else if( e.Command == ApplicationCommands.Copy ) - { - e.Handled = true; - this.ExecuteCopy(); - } - else if( e.Command == ApplicationCommands.Paste ) - { - e.Handled = true; - - string clipboardContent = ( string )Clipboard.GetDataObject().GetData( "System.String" ); - this.Replace( clipboardContent, this.SelectionStart, this.SelectionLength ); - } - else - { - RoutedUICommand routedUICommand = e.Command as RoutedUICommand; - - if( ( routedUICommand != null ) - && ( ( routedUICommand.Name == "Space" ) || ( routedUICommand.Name == "ShiftSpace" ) ) ) - { - e.Handled = true; - this.ProcessTextInput( " " ); - } - } -} - -private void CanExecuteDelete( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - e.CanExecute = this.CanDelete( this.SelectionStart, this.SelectionLength, true, this.MaskedTextProvider.Clone() as MaskedTextProvider ); - e.Handled = true; - - if( ( !e.CanExecute ) && ( this.BeepOnError ) ) - System.Media.SystemSounds.Beep.Play(); -} - -private void CanExecuteDeletePreviousWord( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - bool canDeletePreviousWord = ( !this.IsReadOnly ) && ( EditingCommands.SelectLeftByWord.CanExecute( null, this as IInputElement ) ); - - if( canDeletePreviousWord ) - { - int cachedSelectionStart = this.SelectionStart; - int cachedSelectionLength = this.SelectionLength; - - EditingCommands.SelectLeftByWord.Execute( null, this as IInputElement ); - - canDeletePreviousWord = this.CanDelete( this.SelectionStart, this.SelectionLength, false, this.MaskedTextProvider.Clone() as MaskedTextProvider ); - - if( !canDeletePreviousWord ) - { - this.SelectionStart = cachedSelectionStart; - this.SelectionLength = cachedSelectionLength; - } - } - - e.CanExecute = canDeletePreviousWord; - e.Handled = true; - - if( ( !e.CanExecute ) && ( this.BeepOnError ) ) - System.Media.SystemSounds.Beep.Play(); -} - -private void CanExecuteDeleteNextWord( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - bool canDeleteNextWord = ( !this.IsReadOnly ) && ( EditingCommands.SelectRightByWord.CanExecute( null, this as IInputElement ) ); - - if( canDeleteNextWord ) - { - int cachedSelectionStart = this.SelectionStart; - int cachedSelectionLength = this.SelectionLength; - - EditingCommands.SelectRightByWord.Execute( null, this as IInputElement ); - - canDeleteNextWord = this.CanDelete( this.SelectionStart, this.SelectionLength, true, this.MaskedTextProvider.Clone() as MaskedTextProvider ); - - if( !canDeleteNextWord ) - { - this.SelectionStart = cachedSelectionStart; - this.SelectionLength = cachedSelectionLength; - } - } - - e.CanExecute = canDeleteNextWord; - e.Handled = true; - - if( ( !e.CanExecute ) && ( this.BeepOnError ) ) - System.Media.SystemSounds.Beep.Play(); -} - -private void CanExecuteBackspace( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - e.CanExecute = this.CanDelete( this.SelectionStart, this.SelectionLength, false, this.MaskedTextProvider.Clone() as MaskedTextProvider ); - e.Handled = true; - - if( ( !e.CanExecute ) && ( this.BeepOnError ) ) - System.Media.SystemSounds.Beep.Play(); -} - -private void CanExecuteCut( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - bool canCut = ( !this.IsReadOnly ) && ( this.SelectionLength > 0 ); - - if( canCut ) - { - int endPosition = ( this.SelectionLength > 0 ) ? ( ( this.SelectionStart + this.SelectionLength ) - 1 ) : this.SelectionStart; - - MaskedTextProvider provider = m_maskedTextProvider.Clone() as MaskedTextProvider; - - canCut = provider.RemoveAt( this.SelectionStart, endPosition ); - } - - e.CanExecute = canCut; - e.Handled = true; - - if( ( !canCut ) && ( this.BeepOnError ) ) - System.Media.SystemSounds.Beep.Play(); -} - -private void CanExecutePaste( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - bool canPaste = false; - - if( !this.IsReadOnly ) - { - string clipboardContent = string.Empty; - - try - { - clipboardContent = ( string )Clipboard.GetDataObject().GetData( "System.String" ); - - if( clipboardContent != null ) - { - MaskedTextProvider provider = ( MaskedTextProvider )m_maskedTextProvider.Clone(); - int caretIndex; - canPaste = this.CanReplace( provider, clipboardContent, this.SelectionStart, this.SelectionLength, this.RejectInputOnFirstFailure, out caretIndex ); - } - } - catch - { - } - } - - e.CanExecute = canPaste; - e.Handled = true; - - if( ( !e.CanExecute ) && ( this.BeepOnError ) ) - System.Media.SystemSounds.Beep.Play(); -} - -private void CanExecuteCopy( object sender, CanExecuteRoutedEventArgs e ) -{ - if( m_maskIsNull ) - return; - - e.CanExecute = !m_maskedTextProvider.IsPassword; - e.Handled = true; - - if( ( !e.CanExecute ) && ( this.BeepOnError ) ) - System.Media.SystemSounds.Beep.Play(); -} - -private void ExecuteCopy() -{ - string selectedText = this.GetSelectedText(); - try - { - new UIPermission( UIPermissionClipboard.AllClipboard ).Demand(); - - if( selectedText.Length == 0 ) - { - Clipboard.Clear(); - } - else - { - Clipboard.SetText( selectedText ); - } - } - catch( SecurityException ) - { - } -} - -private void ToggleInsertExecutedCallback( object sender, ExecutedRoutedEventArgs e ) -{ - m_insertToggled = !m_insertToggled; -} - -#endregion COMMANDS - -#region DRAG DROP - -private void PreviewQueryContinueDragCallback( object sender, QueryContinueDragEventArgs e ) -{ - if( m_maskIsNull ) - return; - - e.Action = DragAction.Cancel; - e.Handled = true; -} - -protected override void OnDragEnter( DragEventArgs e ) -{ - if( !m_maskIsNull ) - { - e.Effects = DragDropEffects.None; - e.Handled = true; - } - - base.OnDragEnter( e ); -} - -protected override void OnDragOver( DragEventArgs e ) -{ - if( !m_maskIsNull ) - { - e.Effects = DragDropEffects.None; - e.Handled = true; - } - - base.OnDragOver( e ); -} - -#endregion DRAG DROP - - -#region VALUE FROM TEXT - -protected override bool QueryValueFromTextCore( string text, out object value ) -{ - Type valueDataType = this.ValueDataType; - - if( valueDataType != null ) - { - if( ( m_unhandledLiteralsPositions != null ) - && ( m_unhandledLiteralsPositions.Count > 0 ) ) - { - text = m_maskedTextProvider.ToString( false, false, true, 0, m_maskedTextProvider.Length ); - - for( int i = m_unhandledLiteralsPositions.Count - 1; i >= 0; i-- ) - { - text = text.Remove( m_unhandledLiteralsPositions[ i ], 1 ); - } - } - } - - return base.QueryValueFromTextCore( text, out value ); -} - -#endregion VALUE FROM TEXT - -#region TEXT FROM VALUE - -protected override string QueryTextFromValueCore( object value ) -{ - if( ( m_valueToStringMethodInfo != null ) && ( value != null ) ) - { - try - { - string text = ( string )m_valueToStringMethodInfo.Invoke( value, new object[] { m_formatSpecifier, this.GetActiveFormatProvider() } ); - return text; - } - catch - { - } - } - - return base.QueryTextFromValueCore( value ); -} - -#endregion TEXT FROM VALUE - - -#region PROTECTED METHODS - -protected virtual char[] GetMaskCharacters() -{ - return MaskedTextBox.MaskChars; -} - -private MaskedTextProvider CreateMaskedTextProvider( string mask ) -{ - return this.CreateMaskedTextProvider( - mask, - this.GetCultureInfo(), - this.AllowPromptAsInput, - this.PromptChar, - MaskedTextBox.DefaultPasswordChar, - this.RestrictToAscii ); -} - -protected virtual MaskedTextProvider CreateMaskedTextProvider( - string mask, - CultureInfo cultureInfo, - bool allowPromptAsInput, - char promptChar, - char passwordChar, - bool restrictToAscii ) -{ - MaskedTextProvider provider = new MaskedTextProvider( - mask, - cultureInfo, - allowPromptAsInput, - promptChar, - passwordChar, - restrictToAscii ); - - provider.ResetOnPrompt = this.ResetOnPrompt; - provider.ResetOnSpace = this.ResetOnSpace; - provider.SkipLiterals = this.SkipLiterals; - - provider.IncludeLiterals = true; - provider.IncludePrompt = true; - - provider.IsPassword = false; - - return provider; -} - -internal override void OnIMECompositionEnded( CachedTextInfo cachedTextInfo ) -{ - // End of IME Composition. Restore the critical infos. - this.ForceText( cachedTextInfo.Text, false ); - this.CaretIndex = cachedTextInfo.CaretIndex; - this.SelectionStart = cachedTextInfo.SelectionStart; - this.SelectionLength = cachedTextInfo.SelectionLength; -} - -protected override void OnTextInput( System.Windows.Input.TextCompositionEventArgs e ) -{ - if( this.IsInIMEComposition ) - this.EndIMEComposition(); - - if( ( m_maskIsNull ) || ( m_maskedTextProvider == null ) || ( this.IsReadOnly ) ) - { - base.OnTextInput( e ); - return; - } - - e.Handled = true; - - if( this.CharacterCasing == CharacterCasing.Upper ) - { - this.ProcessTextInput( e.Text.ToUpper() ); - } - else if( this.CharacterCasing == CharacterCasing.Lower ) - { - this.ProcessTextInput( e.Text.ToLower() ); - } - else - { - this.ProcessTextInput( e.Text ); - } - - base.OnTextInput( e ); -} - -private void ProcessTextInput( string text ) -{ - if( text.Length == 1 ) - { - string textOutput = this.MaskedTextOutput; - - int caretIndex; - if( this.PlaceChar( text[ 0 ], this.SelectionStart, this.SelectionLength, this.IsOverwriteMode, out caretIndex ) ) - { - if( this.MaskedTextOutput != textOutput ) - this.RefreshCurrentText( false ); - - this.SelectionStart = caretIndex + 1; - } - else - { - if( this.BeepOnError ) - System.Media.SystemSounds.Beep.Play(); - } - - if( this.SelectionLength > 0 ) - this.SelectionLength = 0; - } - else - { - this.Replace( text, this.SelectionStart, this.SelectionLength ); - } -} - -protected override void ValidateValue( object value ) -{ - base.ValidateValue( value ); - - // Validate if it fits in the mask - if( !m_maskIsNull ) - { - string representation = this.GetTextFromValue( value ); - - MaskedTextProvider provider = m_maskedTextProvider.Clone() as MaskedTextProvider; - - if( !provider.VerifyString( representation ) ) - throw new ArgumentException( "The value representation '" + representation + "' does not match the mask.", "value" ); - } -} - -#endregion PROTECTED METHODS - - -#region INTERNAL PROPERTIES - -internal bool IsForcingMask -{ - get - { - return m_forcingMask; - } -} - -internal string FormatSpecifier -{ - get - { - return m_formatSpecifier; - } - set - { - m_formatSpecifier = value; - } -} - -internal override bool IsTextReadyToBeParsed -{ - get - { - return this.IsMaskCompleted; - } -} - -internal override bool GetIsEditTextEmpty() -{ - return ( this.MaskedTextProvider.AssignedEditPositionCount == 0 ); -} - -#endregion INTERNAL PROPERTIES - -#region INTERNAL METHODS - -internal override string GetCurrentText() -{ - if( m_maskIsNull ) - return base.GetCurrentText(); - - string displayText = this.GetFormattedString( m_maskedTextProvider, this.Text ); - - return displayText; -} - -internal override string GetParsableText() -{ - if( m_maskIsNull ) - return base.GetParsableText(); - - bool includePrompt = false; - bool includeLiterals = true; - - if( this.ValueDataType == typeof( string ) ) - { - includePrompt = this.IncludePromptInValue; - includeLiterals = this.IncludeLiteralsInValue; - } - - return m_maskedTextProvider - .ToString( false, includePrompt, includeLiterals, 0, m_maskedTextProvider.Length ); -} - -internal override void OnFormatProviderChanged() -{ - MaskedTextProvider provider = new MaskedTextProvider( this.Mask ); - - m_maskedTextProvider = provider; - - this.RefreshConversionHelpers(); - this.RefreshCurrentText( true ); - - base.OnFormatProviderChanged(); -} - -internal override void RefreshConversionHelpers() -{ - Type type = this.ValueDataType; - - if( ( type == null ) || ( !this.IsNumericValueDataType ) ) - { - m_formatSpecifier = null; - m_valueToStringMethodInfo = null; - m_unhandledLiteralsPositions = null; - return; - } - - m_valueToStringMethodInfo = type.GetMethod( "ToString", new Type[] { typeof( string ), typeof( IFormatProvider ) } ); - - string mask = m_maskedTextProvider.Mask; - IFormatProvider activeFormatProvider = this.GetActiveFormatProvider(); - - char[] maskChars = this.GetMaskCharacters(); - - List unhandledLiteralsPositions; - - m_formatSpecifier = MaskedTextBox.GetFormatSpecifierFromMask( - mask, - maskChars, - activeFormatProvider, - this.IncludeLiteralsInValue, - out unhandledLiteralsPositions ); - - NumberFormatInfo numberFormatInfo = activeFormatProvider.GetFormat( typeof( NumberFormatInfo ) ) as NumberFormatInfo; - - if( numberFormatInfo != null ) - { - string negativeSign = numberFormatInfo.NegativeSign; - - if( m_formatSpecifier.Contains( negativeSign ) ) - { - // We must make sure that the value data type is numeric since we are about to - // set the format specifier to its Positive,Negative,Zero format pattern. - // If we do not do this, the negative symbol would double itself when IncludeLiteralsInValue - // is set to True and a negative symbol is added to the mask as a literal. - Debug.Assert( this.IsNumericValueDataType ); - - m_formatSpecifier = m_formatSpecifier + ";" + m_formatSpecifier + ";" + m_formatSpecifier; - } - else - { - - } - } - - m_unhandledLiteralsPositions = unhandledLiteralsPositions; -} - -internal void SetValueToStringMethodInfo( MethodInfo valueToStringMethodInfo ) -{ - m_valueToStringMethodInfo = valueToStringMethodInfo; -} - -internal void ForceMask( string mask ) -{ - m_forcingMask = true; - - try - { - this.Mask = mask; - } - finally - { - m_forcingMask = false; - } -} - -#endregion INTERNAL METHODS - -#region PRIVATE PROPERTIES - -private bool IsOverwriteMode -{ - get - { - if( !m_maskIsNull ) - { - switch( this.InsertKeyMode ) - { - case InsertKeyMode.Default: - { - return m_insertToggled; - } - - case InsertKeyMode.Insert: - { - return false; - } - - case InsertKeyMode.Overwrite: - { - return true; - } - } - } - - return false; - } -} - -#endregion PRIVATE PROPERTIES - -#region PRIVATE METHODS - -private bool PlaceChar( char ch, int startPosition, int length, bool overwrite, out int caretIndex ) -{ - return this.PlaceChar( m_maskedTextProvider, ch, startPosition, length, overwrite, out caretIndex ); -} - - -private bool PlaceChar( MaskedTextProvider provider, char ch, int startPosition, int length, bool overwrite, out int caretPosition ) -{ - if( this.ShouldQueryAutoCompleteMask( provider.Clone() as MaskedTextProvider, ch, startPosition ) ) - { - AutoCompletingMaskEventArgs e = new AutoCompletingMaskEventArgs( - m_maskedTextProvider.Clone() as MaskedTextProvider, - startPosition, - length, - ch.ToString() ); - - this.OnAutoCompletingMask( e ); - - if( ( !e.Cancel ) && ( e.AutoCompleteStartPosition > -1 ) ) - { - caretPosition = startPosition; - - // AutoComplete the block. - for( int i = 0; i < e.AutoCompleteText.Length; i++ ) - { - if( !this.PlaceCharCore( provider, e.AutoCompleteText[ i ], e.AutoCompleteStartPosition + i, 0, true, out caretPosition ) ) - return false; - } - - caretPosition = e.AutoCompleteStartPosition + e.AutoCompleteText.Length; - return true; - } - } - - return this.PlaceCharCore( provider, ch, startPosition, length, overwrite, out caretPosition ); -} - -private bool ShouldQueryAutoCompleteMask( MaskedTextProvider provider, char ch, int startPosition ) -{ - if( provider.IsEditPosition( startPosition ) ) - { - int nextSeparatorIndex = provider.FindNonEditPositionFrom( startPosition, true ); - - if( nextSeparatorIndex != -1 ) - { - if( provider[ nextSeparatorIndex ].Equals( ch ) ) - { - int previousSeparatorIndex = provider.FindNonEditPositionFrom( startPosition, false ); - - if( provider.FindUnassignedEditPositionInRange( previousSeparatorIndex, nextSeparatorIndex, true ) != -1 ) - { - return true; - } - } - } - } - - return false; -} - -protected virtual void OnAutoCompletingMask( AutoCompletingMaskEventArgs e ) -{ - if( this.AutoCompletingMask != null ) - this.AutoCompletingMask( this, e ); -} - -public event EventHandler AutoCompletingMask; - - -private bool PlaceCharCore( MaskedTextProvider provider, char ch, int startPosition, int length, bool overwrite, out int caretPosition ) -{ - caretPosition = startPosition; - - if( startPosition < m_maskedTextProvider.Length ) - { - MaskedTextResultHint notUsed; - - if( length > 0 ) - { - int endPosition = ( startPosition + length ) - 1; - return provider.Replace( ch, startPosition, endPosition, out caretPosition, out notUsed ); - } - - if( overwrite ) - return provider.Replace( ch, startPosition, out caretPosition, out notUsed ); - - return provider.InsertAt( ch, startPosition, out caretPosition, out notUsed ); - } - - return false; -} - -internal void Replace( string text, int startPosition, int selectionLength ) -{ - MaskedTextProvider provider = ( MaskedTextProvider )m_maskedTextProvider.Clone(); - int tentativeCaretIndex; - - if( this.CanReplace( provider, text, startPosition, selectionLength, this.RejectInputOnFirstFailure, out tentativeCaretIndex ) ) - { - System.Diagnostics.Debug.WriteLine( "Replace caret index to: " + tentativeCaretIndex.ToString() ); - - bool mustRefreshText = this.MaskedTextOutput != provider.ToString(); - m_maskedTextProvider = provider; - - if( mustRefreshText ) - this.RefreshCurrentText( false ); - - this.CaretIndex = tentativeCaretIndex + 1; - } - else - { - if( this.BeepOnError ) - System.Media.SystemSounds.Beep.Play(); - } -} - -internal virtual bool CanReplace( MaskedTextProvider provider, string text, int startPosition, int selectionLength, bool rejectInputOnFirstFailure, out int tentativeCaretIndex ) -{ - int endPosition = ( startPosition + selectionLength ) - 1; - tentativeCaretIndex = -1; - - - bool success = false; - - foreach( char ch in text ) - { - if( !m_maskedTextProvider.VerifyEscapeChar( ch, startPosition ) ) - { - int editPositionFrom = provider.FindEditPositionFrom( startPosition, true ); - - if( editPositionFrom == MaskedTextProvider.InvalidIndex ) - break; - - startPosition = editPositionFrom; - } - - int length = ( endPosition >= startPosition ) ? 1 : 0; - bool overwrite = length > 0; - - if( this.PlaceChar( provider, ch, startPosition, length, overwrite, out tentativeCaretIndex ) ) - { - // Only one successfully inserted character is enough to declare the replace operation successful. - success = true; - - startPosition = tentativeCaretIndex + 1; - } - else if( rejectInputOnFirstFailure ) - { - return false; - } - } - - if( ( selectionLength > 0 ) && ( startPosition <= endPosition ) ) - { - - // Erase the remaining of the assigned edit character. - int notUsed; - MaskedTextResultHint notUsedHint; - if( !provider.RemoveAt( startPosition, endPosition, out notUsed, out notUsedHint ) ) - success = false; - } - - return success; -} - -private bool CanDelete( int startPosition, int selectionLength, bool deleteForward, MaskedTextProvider provider ) -{ - if( this.IsReadOnly ) - return false; - - - if( selectionLength == 0 ) - { - if( !deleteForward ) - { - if( startPosition == 0 ) - return false; - - startPosition--; - } - else if( ( startPosition + selectionLength ) == provider.Length ) - { - return false; - } - } - - MaskedTextResultHint notUsed; - int tentativeCaretPosition = startPosition; - - int endPosition = ( selectionLength > 0 ) ? ( ( startPosition + selectionLength ) - 1 ) : startPosition; - - bool success = provider.RemoveAt( startPosition, endPosition, out tentativeCaretPosition, out notUsed ); - - return success; -} - -private void Delete( int startPosition, int selectionLength, bool deleteForward ) -{ - if( this.IsReadOnly ) - return; - - - if( selectionLength == 0 ) - { - if( !deleteForward ) - { - if( startPosition == 0 ) - return; - - startPosition--; - } - else if( ( startPosition + selectionLength ) == m_maskedTextProvider.Length ) - { - return; - } - } - - MaskedTextResultHint hint; - int tentativeCaretPosition = startPosition; - - int endPosition = ( selectionLength > 0 ) ? ( ( startPosition + selectionLength ) - 1 ) : startPosition; - - string oldTextOutput = this.MaskedTextOutput; - - bool success = m_maskedTextProvider.RemoveAt( startPosition, endPosition, out tentativeCaretPosition, out hint ); - - if( !success ) - { - if( this.BeepOnError ) - System.Media.SystemSounds.Beep.Play(); - - return; - } - - if( this.MaskedTextOutput != oldTextOutput ) - { - this.RefreshCurrentText( false ); - } - else if( selectionLength > 0 ) - { - tentativeCaretPosition = startPosition; - } - else if( hint == MaskedTextResultHint.NoEffect ) - { - if( deleteForward ) - { - tentativeCaretPosition = m_maskedTextProvider.FindEditPositionFrom( startPosition, true ); - } - else - { - if( m_maskedTextProvider.FindAssignedEditPositionFrom( startPosition, true ) == MaskedTextProvider.InvalidIndex ) - { - tentativeCaretPosition = m_maskedTextProvider.FindAssignedEditPositionFrom( startPosition, false ); - } - else - { - tentativeCaretPosition = m_maskedTextProvider.FindEditPositionFrom( startPosition, false ); - } - - if( tentativeCaretPosition != MaskedTextProvider.InvalidIndex ) - tentativeCaretPosition++; - } - - if( tentativeCaretPosition == MaskedTextProvider.InvalidIndex ) - tentativeCaretPosition = startPosition; - } - else if( !deleteForward ) - { - tentativeCaretPosition = startPosition; - } - - this.CaretIndex = tentativeCaretPosition; -} - -private string MaskedTextOutput -{ - get - { - System.Diagnostics.Debug.Assert( m_maskedTextProvider.EditPositionCount > 0 ); - - return m_maskedTextProvider.ToString(); - } -} - -private string GetRawText() -{ - if( m_maskIsNull ) - return this.Text; - - return MaskedTextBox.GetRawText( m_maskedTextProvider ); -} - -private string GetFormattedString( MaskedTextProvider provider, string text ) -{ - if( provider.Mask.StartsWith( ">" ) ) - return text.ToUpper(); - if( provider.Mask.StartsWith( "<" ) ) - return text.ToLower(); - - //System.Diagnostics.Debug.Assert( provider.EditPositionCount > 0 ); - - - bool includePrompt = ( this.IsReadOnly ) ? false : ( !this.HidePromptOnLeave || this.IsFocused ); - - string displayString = provider.ToString( false, includePrompt, true, 0, m_maskedTextProvider.Length ); - - return displayString; -} - -private string GetSelectedText() -{ - System.Diagnostics.Debug.Assert( !m_maskIsNull ); - - int selectionLength = this.SelectionLength; - - if( selectionLength == 0 ) - return string.Empty; - - bool includePrompt = ( this.ClipboardMaskFormat & MaskFormat.IncludePrompt ) != MaskFormat.ExcludePromptAndLiterals; - bool includeLiterals = ( this.ClipboardMaskFormat & MaskFormat.IncludeLiterals ) != MaskFormat.ExcludePromptAndLiterals; - - return m_maskedTextProvider.ToString( true, includePrompt, includeLiterals, this.SelectionStart, selectionLength ); -} - -#endregion PRIVATE METHODS - -#region PRIVATE FIELDS - -private MaskedTextProvider m_maskedTextProvider; // = null; -private bool m_insertToggled; // = false; -private bool m_maskIsNull = true; -private bool m_forcingMask; // = false; - -List m_unhandledLiteralsPositions; // = null; -private string m_formatSpecifier; -private MethodInfo m_valueToStringMethodInfo; // = null; - -#endregion PRIVATE FIELDS -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryMoveFocusEventArgs.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryMoveFocusEventArgs.cs deleted file mode 100644 index c4052f237..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryMoveFocusEventArgs.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System.Windows; -using System.Windows.Input; - -namespace HandyControl.Controls; - -[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1003:UseGenericEventHandlerInstances")] -public delegate void QueryMoveFocusEventHandler(object sender, QueryMoveFocusEventArgs e); - -public class QueryMoveFocusEventArgs : RoutedEventArgs -{ - //default CTOR private to prevent its usage. - private QueryMoveFocusEventArgs() - { - } - - //internal to prevent anybody from building this type of event. - internal QueryMoveFocusEventArgs(FocusNavigationDirection direction, bool reachedMaxLength) - : base(AutoSelectTextBox.QueryMoveFocusEvent) - { - m_navigationDirection = direction; - m_reachedMaxLength = reachedMaxLength; - } - - public FocusNavigationDirection FocusNavigationDirection - { - get - { - return m_navigationDirection; - } - } - - public bool ReachedMaxLength - { - get - { - return m_reachedMaxLength; - } - } - - public bool CanMoveFocus - { - get - { - return m_canMove; - } - set - { - m_canMove = value; - } - } - - private FocusNavigationDirection m_navigationDirection; - private bool m_reachedMaxLength; - private bool m_canMove = true; //defaults to true... if nobody does nothing, then its capable of moving focus. - -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryTextFromValueEventArgs.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryTextFromValueEventArgs.cs deleted file mode 100644 index 85b49d791..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryTextFromValueEventArgs.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System; - -namespace HandyControl.Controls; - -public class QueryTextFromValueEventArgs : EventArgs -{ - public QueryTextFromValueEventArgs(object value, string text) - { - m_value = value; - m_text = text; - } - - #region Value Property - - private object m_value; - - public object Value - { - get { return m_value; } - } - - #endregion Value Property - - #region Text Property - - private string m_text; - - public string Text - { - get { return m_text; } - set { m_text = value; } - } - - #endregion Text Property -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryValueFromTextEventArgs.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryValueFromTextEventArgs.cs deleted file mode 100644 index 79f7f6425..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/QueryValueFromTextEventArgs.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; - -namespace HandyControl.Controls; - -public class QueryValueFromTextEventArgs : EventArgs -{ - public QueryValueFromTextEventArgs(string text, object value) - { - m_text = text; - m_value = value; - } - - #region Text Property - - private string m_text; - - public string Text - { - get { return m_text; } - } - - #endregion Text Property - - #region Value Property - - private object m_value; - - public object Value - { - get { return m_value; } - set { m_value = value; } - } - - #endregion Value Property - - #region HasParsingError Property - - private bool m_hasParsingError; - - public bool HasParsingError - { - get { return m_hasParsingError; } - set { m_hasParsingError = value; } - } - - #endregion HasParsingError Property - -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/TreeHelper.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/TreeHelper.cs deleted file mode 100644 index 84c1cdeb8..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/TreeHelper.cs +++ /dev/null @@ -1,219 +0,0 @@ -using System; -using System.Windows; -using System.Windows.Controls.Primitives; -using System.Windows.Media; - -namespace HandyControl.Controls; - -internal static class TreeHelper -{ - /// - /// Tries its best to return the specified element's parent. It will - /// try to find, in this order, the VisualParent, LogicalParent, LogicalTemplatedParent. - /// It only works for Visual, FrameworkElement or FrameworkContentElement. - /// - /// The element to which to return the parent. It will only - /// work if element is a Visual, a FrameworkElement or a FrameworkContentElement. - /// If the logical parent is not found (Parent), we check the TemplatedParent - /// (see FrameworkElement.Parent documentation). But, we never actually witnessed - /// this situation. - public static DependencyObject GetParent(DependencyObject element) - { - return TreeHelper.GetParent(element, true); - } - - private static DependencyObject GetParent(DependencyObject element, bool recurseIntoPopup) - { - if (recurseIntoPopup) - { - // Case 126732 : To correctly detect parent of a popup we must do that exception case - Popup popup = element as Popup; - - if ((popup != null) && (popup.PlacementTarget != null)) - return popup.PlacementTarget; - } - - Visual visual = element as Visual; - DependencyObject parent = (visual == null) ? null : VisualTreeHelper.GetParent(visual); - - if (parent == null) - { - // No Visual parent. Check in the logical tree. - FrameworkElement fe = element as FrameworkElement; - - if (fe != null) - { - parent = fe.Parent; - - if (parent == null) - { - parent = fe.TemplatedParent; - } - } - else - { - FrameworkContentElement fce = element as FrameworkContentElement; - - if (fce != null) - { - parent = fce.Parent; - - if (parent == null) - { - parent = fce.TemplatedParent; - } - } - } - } - - return parent; - } - - /// - /// This will search for a parent of the specified type. - /// - /// The type of the element to find - /// The node where the search begins. This element is not checked. - /// Returns the found element. Null if nothing is found. - public static T FindParent(DependencyObject startingObject) where T : DependencyObject - { - return TreeHelper.FindParent(startingObject, false, null); - } - - /// - /// This will search for a parent of the specified type. - /// - /// The type of the element to find - /// The node where the search begins. - /// Should the specified startingObject be checked first. - /// Returns the found element. Null if nothing is found. - public static T FindParent(DependencyObject startingObject, bool checkStartingObject) where T : DependencyObject - { - return TreeHelper.FindParent(startingObject, checkStartingObject, null); - } - - /// - /// This will search for a parent of the specified type. - /// - /// The type of the element to find - /// The node where the search begins. - /// Should the specified startingObject be checked first. - /// Provide a callback to check additional properties - /// of the found elements. Can be left Null if no additional criteria are needed. - /// Returns the found element. Null if nothing is found. - /// Button button = TreeHelper.FindParent<Button>( this, foundChild => foundChild.Focusable ); - public static T FindParent(DependencyObject startingObject, bool checkStartingObject, Func additionalCheck) where T : DependencyObject - { - T foundElement; - DependencyObject parent = (checkStartingObject ? startingObject : TreeHelper.GetParent(startingObject, true)); - - while (parent != null) - { - foundElement = parent as T; - - if (foundElement != null) - { - if (additionalCheck == null) - { - return foundElement; - } - else - { - if (additionalCheck(foundElement)) - return foundElement; - } - } - - parent = TreeHelper.GetParent(parent, true); - } - - return null; - } - - /// - /// This will search for a child of the specified type. The search is performed - /// hierarchically, breadth first (as opposed to depth first). - /// - /// The type of the element to find - /// The root of the tree to search for. This element itself is not checked. - /// Returns the found element. Null if nothing is found. - public static T FindChild(DependencyObject parent) where T : DependencyObject - { - return TreeHelper.FindChild(parent, null); - } - - /// - /// This will search for a child of the specified type. The search is performed - /// hierarchically, breadth first (as opposed to depth first). - /// - /// The type of the element to find - /// The root of the tree to search for. This element itself is not checked. - /// Provide a callback to check additional properties - /// of the found elements. Can be left Null if no additional criteria are needed. - /// Returns the found element. Null if nothing is found. - /// Button button = TreeHelper.FindChild<Button>( this, foundChild => foundChild.Focusable ); - public static T FindChild(DependencyObject parent, Func additionalCheck) where T : DependencyObject - { - int childrenCount = VisualTreeHelper.GetChildrenCount(parent); - T child; - - for (int index = 0; index < childrenCount; index++) - { - child = VisualTreeHelper.GetChild(parent, index) as T; - - if (child != null) - { - if (additionalCheck == null) - { - return child; - } - else - { - if (additionalCheck(child)) - return child; - } - } - } - - for (int index = 0; index < childrenCount; index++) - { - child = TreeHelper.FindChild(VisualTreeHelper.GetChild(parent, index), additionalCheck); - - if (child != null) - return child; - } - - return null; - } - - /// - /// Returns true if the specified element is a child of parent somewhere in the visual - /// tree. This method will work for Visual, FrameworkElement and FrameworkContentElement. - /// - /// The element that is potentially a child of the specified parent. - /// The element that is potentially a parent of the specified element. - public static bool IsDescendantOf(DependencyObject element, DependencyObject parent) - { - return TreeHelper.IsDescendantOf(element, parent, true); - } - - /// - /// Returns true if the specified element is a child of parent somewhere in the visual - /// tree. This method will work for Visual, FrameworkElement and FrameworkContentElement. - /// - /// The element that is potentially a child of the specified parent. - /// The element that is potentially a parent of the specified element. - /// - public static bool IsDescendantOf(DependencyObject element, DependencyObject parent, bool recurseIntoPopup) - { - while (element != null) - { - if (element == parent) - return true; - - element = TreeHelper.GetParent(element, recurseIntoPopup); - } - - return false; - } -} diff --git a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/ValueRangeTextBox.cs b/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/ValueRangeTextBox.cs deleted file mode 100644 index 3805439f4..000000000 --- a/src/Shared/HandyControl_Shared/HandyControls/Controls/MaskedTextBox/ValueRangeTextBox.cs +++ /dev/null @@ -1,1185 +0,0 @@ -using System; -using System.Collections.Specialized; -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; - -namespace HandyControl.Controls; - -public class ValueRangeTextBox : AutoSelectTextBox -{ - static ValueRangeTextBox() - { - ValueRangeTextBox.TextProperty.OverrideMetadata(typeof(ValueRangeTextBox), - new FrameworkPropertyMetadata( - null, - new CoerceValueCallback(ValueRangeTextBox.TextCoerceValueCallback))); - - ValueRangeTextBox.AcceptsReturnProperty.OverrideMetadata(typeof(ValueRangeTextBox), - new FrameworkPropertyMetadata( - false, null, new CoerceValueCallback(ValueRangeTextBox.AcceptsReturnCoerceValueCallback))); - - ValueRangeTextBox.AcceptsTabProperty.OverrideMetadata(typeof(ValueRangeTextBox), - new FrameworkPropertyMetadata( - false, null, new CoerceValueCallback(ValueRangeTextBox.AcceptsTabCoerceValueCallback))); - } - - public ValueRangeTextBox() - { - } - - #region AcceptsReturn Property - - private static object AcceptsReturnCoerceValueCallback(DependencyObject sender, object value) - { - bool acceptsReturn = (bool)value; - - if (acceptsReturn) - throw new NotSupportedException("The ValueRangeTextBox does not support the AcceptsReturn property."); - - return false; - } - - #endregion AcceptsReturn Property - - #region AcceptsTab Property - - private static object AcceptsTabCoerceValueCallback(DependencyObject sender, object value) - { - bool acceptsTab = (bool)value; - - if (acceptsTab) - throw new NotSupportedException("The ValueRangeTextBox does not support the AcceptsTab property."); - - return false; - } - - #endregion AcceptsTab Property - - #region BeepOnError Property - - public bool BeepOnError - { - get - { - return (bool)GetValue(BeepOnErrorProperty); - } - set - { - SetValue(BeepOnErrorProperty, value); - } - } - - public static readonly DependencyProperty BeepOnErrorProperty = - DependencyProperty.Register("BeepOnError", typeof(bool), typeof(ValueRangeTextBox), new UIPropertyMetadata(false)); - - #endregion BeepOnError Property - - #region FormatProvider Property - - public IFormatProvider FormatProvider - { - get - { - return (IFormatProvider)GetValue(FormatProviderProperty); - } - set - { - SetValue(FormatProviderProperty, value); - } - } - - public static readonly DependencyProperty FormatProviderProperty = - DependencyProperty.Register("FormatProvider", typeof(IFormatProvider), typeof(ValueRangeTextBox), - new UIPropertyMetadata(null, - new PropertyChangedCallback(ValueRangeTextBox.FormatProviderPropertyChangedCallback))); - - private static void FormatProviderPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) - { - ValueRangeTextBox valueRangeTextBox = (ValueRangeTextBox)sender; - - if (!valueRangeTextBox.IsInitialized) - return; - - valueRangeTextBox.OnFormatProviderChanged(); - } - - internal virtual void OnFormatProviderChanged() - { - this.RefreshConversionHelpers(); - this.RefreshCurrentText(false); - this.RefreshValue(); - } - - #endregion FormatProvider Property - - #region MinValue Property - - public object MinValue - { - get - { - return (object)GetValue(MinValueProperty); - } - set - { - SetValue(MinValueProperty, value); - } - } - - public static readonly DependencyProperty MinValueProperty = - DependencyProperty.Register("MinValue", typeof(object), typeof(ValueRangeTextBox), - new UIPropertyMetadata( - null, - null, - new CoerceValueCallback(ValueRangeTextBox.MinValueCoerceValueCallback))); - - private static object MinValueCoerceValueCallback(DependencyObject sender, object value) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (!valueRangeTextBox.IsInitialized) - return DependencyProperty.UnsetValue; - - if (value == null) - return value; - - Type type = valueRangeTextBox.ValueDataType; - - if (type == null) - throw new InvalidOperationException("An attempt was made to set a minimum value when the ValueDataType property is null."); - - if (valueRangeTextBox.IsFinalizingInitialization) - value = ValueRangeTextBox.ConvertValueToDataType(value, valueRangeTextBox.ValueDataType); - - if (value.GetType() != type) - throw new ArgumentException("The value is not of type " + type.Name + ".", "MinValue"); - - IComparable comparable = value as IComparable; - - if (comparable == null) - throw new InvalidOperationException("MinValue does not implement the IComparable interface."); - - // ValidateValueInRange will throw if it must. - object maxValue = valueRangeTextBox.MaxValue; - - valueRangeTextBox.ValidateValueInRange(value, maxValue, valueRangeTextBox.Value); - - return value; - } - - #endregion MinValue Property - - #region MaxValue Property - - public object MaxValue - { - get - { - return (object)GetValue(MaxValueProperty); - } - set - { - SetValue(MaxValueProperty, value); - } - } - - public static readonly DependencyProperty MaxValueProperty = - DependencyProperty.Register("MaxValue", typeof(object), typeof(ValueRangeTextBox), - new UIPropertyMetadata( - null, - null, - new CoerceValueCallback(MaxValueCoerceValueCallback))); - - private static object MaxValueCoerceValueCallback(DependencyObject sender, object value) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (!valueRangeTextBox.IsInitialized) - return DependencyProperty.UnsetValue; - - if (value == null) - return value; - - Type type = valueRangeTextBox.ValueDataType; - - if (type == null) - throw new InvalidOperationException("An attempt was made to set a maximum value when the ValueDataType property is null."); - - if (valueRangeTextBox.IsFinalizingInitialization) - value = ValueRangeTextBox.ConvertValueToDataType(value, valueRangeTextBox.ValueDataType); - - if (value.GetType() != type) - throw new ArgumentException("The value is not of type " + type.Name + ".", "MinValue"); - - IComparable comparable = value as IComparable; - - if (comparable == null) - throw new InvalidOperationException("MaxValue does not implement the IComparable interface."); - - object minValue = valueRangeTextBox.MinValue; - - // ValidateValueInRange will throw if it must. - valueRangeTextBox.ValidateValueInRange(minValue, value, valueRangeTextBox.Value); - - return value; - } - - #endregion MaxValue Property - - #region NullValue Property - - public object NullValue - { - get - { - return (object)GetValue(NullValueProperty); - } - set - { - SetValue(NullValueProperty, value); - } - } - - public static readonly DependencyProperty NullValueProperty = - DependencyProperty.Register("NullValue", typeof(object), typeof(ValueRangeTextBox), - new UIPropertyMetadata( - null, - new PropertyChangedCallback(ValueRangeTextBox.NullValuePropertyChangedCallback), - new CoerceValueCallback(NullValueCoerceValueCallback))); - - private static object NullValueCoerceValueCallback(DependencyObject sender, object value) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (!valueRangeTextBox.IsInitialized) - return DependencyProperty.UnsetValue; - - if ((value == null) || (value == DBNull.Value)) - return value; - - Type type = valueRangeTextBox.ValueDataType; - - if (type == null) - throw new InvalidOperationException("An attempt was made to set a null value when the ValueDataType property is null."); - - if (valueRangeTextBox.IsFinalizingInitialization) - value = ValueRangeTextBox.ConvertValueToDataType(value, valueRangeTextBox.ValueDataType); - - if (value.GetType() != type) - throw new ArgumentException("The value is not of type " + type.Name + ".", "NullValue"); - - return value; - } - - private static void NullValuePropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (e.OldValue == null) - { - if (valueRangeTextBox.Value == null) - valueRangeTextBox.RefreshValue(); - } - else - { - if (e.OldValue.Equals(valueRangeTextBox.Value)) - valueRangeTextBox.RefreshValue(); - } - } - - #endregion NullValue Property - - #region Value Property - - public object Value - { - get - { - return (object)GetValue(ValueProperty); - } - set - { - SetValue(ValueProperty, value); - } - } - - public static readonly DependencyProperty ValueProperty = - DependencyProperty.Register("Value", typeof(object), typeof(ValueRangeTextBox), - new FrameworkPropertyMetadata( - null, - FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, - new PropertyChangedCallback(ValueRangeTextBox.ValuePropertyChangedCallback), - new CoerceValueCallback(ValueRangeTextBox.ValueCoerceValueCallback))); - - private static object ValueCoerceValueCallback(object sender, object value) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (!valueRangeTextBox.IsInitialized) - return DependencyProperty.UnsetValue; - - if (valueRangeTextBox.IsFinalizingInitialization) - value = ValueRangeTextBox.ConvertValueToDataType(value, valueRangeTextBox.ValueDataType); - - if (!valueRangeTextBox.IsForcingValue) - valueRangeTextBox.ValidateValue(value); - - return value; - } - - private static void ValuePropertyChangedCallback(object sender, DependencyPropertyChangedEventArgs e) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (valueRangeTextBox.IsForcingValue) - return; - - // The ValueChangedCallback can be raised even though both values are the same since the property - // datatype is Object. - if (object.Equals(e.NewValue, e.OldValue)) - return; - - valueRangeTextBox.IsInValueChanged = true; - try - { - valueRangeTextBox.Text = valueRangeTextBox.GetTextFromValue(e.NewValue); - } - finally - { - valueRangeTextBox.IsInValueChanged = false; - } - } - - #endregion Value Property - - #region ValueDataType Property - - public Type ValueDataType - { - get - { - return (Type)GetValue(ValueDataTypeProperty); - } - set - { - SetValue(ValueDataTypeProperty, value); - } - } - - public static readonly DependencyProperty ValueDataTypeProperty = - DependencyProperty.Register("ValueDataType", typeof(Type), typeof(ValueRangeTextBox), - new UIPropertyMetadata( - null, - new PropertyChangedCallback(ValueRangeTextBox.ValueDataTypePropertyChangedCallback), - new CoerceValueCallback(ValueRangeTextBox.ValueDataTypeCoerceValueCallback))); - - private static object ValueDataTypeCoerceValueCallback(DependencyObject sender, object value) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (!valueRangeTextBox.IsInitialized) - return DependencyProperty.UnsetValue; - - Type valueDataType = value as Type; - - try - { - valueRangeTextBox.ValidateDataType(valueDataType); - } - catch (Exception exception) - { - throw new ArgumentException("An error occured while trying to change the ValueDataType.", exception); - } - - return value; - } - - private static void ValueDataTypePropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - Type valueDataType = e.NewValue as Type; - - valueRangeTextBox.IsNumericValueDataType = ValueRangeTextBox.IsNumericType(valueDataType); - - valueRangeTextBox.RefreshConversionHelpers(); - - valueRangeTextBox.ConvertValuesToDataType(valueDataType); - } - - internal virtual void ValidateDataType(Type type) - { - // Null will always be valid and will reset the MinValue, MaxValue, NullValue and Value to null. - if (type == null) - return; - - // We use InvariantCulture instead of the active format provider since the FormatProvider is only - // used when the source type is String. When we are converting from a string, we are - // actually converting a value from XAML. Therefore, if the string will have a period as a - // decimal separator. If we were using the active format provider, we could end up expecting a coma - // as the decimal separator and the ChangeType method would throw. - - object minValue = this.MinValue; - - if ((minValue != null) && (minValue.GetType() != type)) - minValue = System.Convert.ChangeType(minValue, type, CultureInfo.InvariantCulture); - - object maxValue = this.MaxValue; - - if ((maxValue != null) && (maxValue.GetType() != type)) - maxValue = System.Convert.ChangeType(maxValue, type, CultureInfo.InvariantCulture); - - object nullValue = this.NullValue; - - if (((nullValue != null) && (nullValue != DBNull.Value)) - && (nullValue.GetType() != type)) - { - nullValue = System.Convert.ChangeType(nullValue, type, CultureInfo.InvariantCulture); - } - - object value = this.Value; - - if (((value != null) && (value != DBNull.Value)) - && (value.GetType() != type)) - { - value = System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture); - } - - if ((minValue != null) || (maxValue != null) - || ((nullValue != null) && (nullValue != DBNull.Value))) - { - // Value comparaisons will occur. Therefore, the aspiring data type must implement IComparable. - - Type iComparable = type.GetInterface("IComparable"); - - if (iComparable == null) - throw new InvalidOperationException("MinValue, MaxValue, and NullValue must implement the IComparable interface."); - } - } - - private void ConvertValuesToDataType(Type type) - { - if (type == null) - { - this.MinValue = null; - this.MaxValue = null; - this.NullValue = null; - - this.Value = null; - - return; - } - - object minValue = this.MinValue; - - if ((minValue != null) && (minValue.GetType() != type)) - this.MinValue = ValueRangeTextBox.ConvertValueToDataType(minValue, type); - - object maxValue = this.MaxValue; - - if ((maxValue != null) && (maxValue.GetType() != type)) - this.MaxValue = ValueRangeTextBox.ConvertValueToDataType(maxValue, type); - - object nullValue = this.NullValue; - - if (((nullValue != null) && (nullValue != DBNull.Value)) - && (nullValue.GetType() != type)) - { - this.NullValue = ValueRangeTextBox.ConvertValueToDataType(nullValue, type); - } - - object value = this.Value; - - if (((value != null) && (value != DBNull.Value)) - && (value.GetType() != type)) - { - this.Value = ValueRangeTextBox.ConvertValueToDataType(value, type); - } - } - - #endregion ValueDataType Property - - #region Text Property - - private static object TextCoerceValueCallback(object sender, object value) - { - ValueRangeTextBox valueRangeTextBox = sender as ValueRangeTextBox; - - if (!valueRangeTextBox.IsInitialized) - return DependencyProperty.UnsetValue; - - if (value == null) - return string.Empty; - - return value; - } - - protected override void OnTextChanged(TextChangedEventArgs e) - { - // If in IME Composition, RefreshValue already returns without doing anything. - this.RefreshValue(); - - base.OnTextChanged(e); - } - - #endregion Text Property - - #region HasValidationError Property - - private static readonly DependencyPropertyKey HasValidationErrorPropertyKey = - DependencyProperty.RegisterReadOnly("HasValidationError", typeof(bool), typeof(ValueRangeTextBox), new UIPropertyMetadata(false)); - - public static readonly DependencyProperty HasValidationErrorProperty = ValueRangeTextBox.HasValidationErrorPropertyKey.DependencyProperty; - - public bool HasValidationError - { - get - { - return (bool)this.GetValue(ValueRangeTextBox.HasValidationErrorProperty); - } - } - - private void SetHasValidationError(bool value) - { - this.SetValue(ValueRangeTextBox.HasValidationErrorPropertyKey, value); - } - - #endregion HasValidationError Property - - #region HasParsingError Property - - private static readonly DependencyPropertyKey HasParsingErrorPropertyKey = - DependencyProperty.RegisterReadOnly("HasParsingError", typeof(bool), typeof(ValueRangeTextBox), new UIPropertyMetadata(false)); - - public static readonly DependencyProperty HasParsingErrorProperty = ValueRangeTextBox.HasParsingErrorPropertyKey.DependencyProperty; - - public bool HasParsingError - { - get - { - return (bool)this.GetValue(ValueRangeTextBox.HasParsingErrorProperty); - } - } - - internal void SetHasParsingError(bool value) - { - this.SetValue(ValueRangeTextBox.HasParsingErrorPropertyKey, value); - } - - #endregion HasParsingError Property - - #region IsValueOutOfRange Property - - private static readonly DependencyPropertyKey IsValueOutOfRangePropertyKey = - DependencyProperty.RegisterReadOnly("IsValueOutOfRange", typeof(bool), typeof(ValueRangeTextBox), new UIPropertyMetadata(false)); - - public static readonly DependencyProperty IsValueOutOfRangeProperty = ValueRangeTextBox.IsValueOutOfRangePropertyKey.DependencyProperty; - - public bool IsValueOutOfRange - { - get - { - return (bool)this.GetValue(ValueRangeTextBox.IsValueOutOfRangeProperty); - } - } - - private void SetIsValueOutOfRange(bool value) - { - this.SetValue(ValueRangeTextBox.IsValueOutOfRangePropertyKey, value); - } - - #endregion IsValueOutOfRange Property - - #region IsInValueChanged property - - internal bool IsInValueChanged - { - get - { - return m_flags[(int)ValueRangeTextBoxFlags.IsInValueChanged]; - } - private set - { - m_flags[(int)ValueRangeTextBoxFlags.IsInValueChanged] = value; - } - } - - #endregion - - #region IsForcingValue property - - internal bool IsForcingValue - { - get - { - return m_flags[(int)ValueRangeTextBoxFlags.IsForcingValue]; - } - private set - { - m_flags[(int)ValueRangeTextBoxFlags.IsForcingValue] = value; - } - } - - #endregion - - #region IsForcingText property - - internal bool IsForcingText - { - get - { - return m_flags[(int)ValueRangeTextBoxFlags.IsForcingText]; - } - private set - { - m_flags[(int)ValueRangeTextBoxFlags.IsForcingText] = value; - } - } - - #endregion - - #region IsNumericValueDataType property - - internal bool IsNumericValueDataType - { - get - { - return m_flags[(int)ValueRangeTextBoxFlags.IsNumericValueDataType]; - } - private set - { - m_flags[(int)ValueRangeTextBoxFlags.IsNumericValueDataType] = value; - } - } - - #endregion - - #region IsTextReadyToBeParsed property - - internal virtual bool IsTextReadyToBeParsed - { - get - { - return true; - } - } - - #endregion - - #region IsInIMEComposition property - - internal bool IsInIMEComposition - { - get - { - return m_imePreCompositionCachedTextInfo != null; - } - } - - #endregion - - #region IsFinalizingInitialization Property - - private bool IsFinalizingInitialization - { - get - { - return m_flags[(int)ValueRangeTextBoxFlags.IsFinalizingInitialization]; - } - set - { - m_flags[(int)ValueRangeTextBoxFlags.IsFinalizingInitialization] = value; - } - } - - #endregion - - #region TEXT FROM VALUE - - public event EventHandler QueryTextFromValue; - - internal string GetTextFromValue(object value) - { - string text = this.QueryTextFromValueCore(value); - - QueryTextFromValueEventArgs e = new QueryTextFromValueEventArgs(value, text); - - this.OnQueryTextFromValue(e); - - return e.Text; - } - - protected virtual string QueryTextFromValueCore(object value) - { - if ((value == null) || (value == DBNull.Value)) - return string.Empty; - - IFormatProvider formatProvider = this.GetActiveFormatProvider(); - - CultureInfo cultureInfo = formatProvider as CultureInfo; - - if (cultureInfo != null) - { - TypeConverter converter = TypeDescriptor.GetConverter(value.GetType()); - - if (converter.CanConvertTo(typeof(string))) - return (string)converter.ConvertTo(null, cultureInfo, value, typeof(string)); - } - - try - { - string result = System.Convert.ToString(value, formatProvider); - - return result; - } - catch - { - } - - return value.ToString(); - } - - private void OnQueryTextFromValue(QueryTextFromValueEventArgs e) - { - if (this.QueryTextFromValue != null) - this.QueryTextFromValue(this, e); - } - - #endregion TEXT FROM VALUE - - #region VALUE FROM TEXT - - public event EventHandler QueryValueFromText; - - internal object GetValueFromText(string text, out bool hasParsingError) - { - object value = null; - bool success = this.QueryValueFromTextCore(text, out value); - - QueryValueFromTextEventArgs e = new QueryValueFromTextEventArgs(text, value); - e.HasParsingError = !success; - - this.OnQueryValueFromText(e); - - hasParsingError = e.HasParsingError; - - return e.Value; - } - - protected virtual bool QueryValueFromTextCore(string text, out object value) - { - value = null; - - Type validatingType = this.ValueDataType; - - text = text.Trim(); - - if (validatingType == null) - return true; - - if (!validatingType.IsValueType && (validatingType != typeof(string))) - return false; - - try - { - value = ChangeTypeHelper.ChangeType(text, validatingType, this.GetActiveFormatProvider()); - } - catch - { - if (this.BeepOnError) - { - System.Media.SystemSounds.Beep.Play(); - } - return false; - } - - return true; - } - - private void OnQueryValueFromText(QueryValueFromTextEventArgs e) - { - if (this.QueryValueFromText != null) - this.QueryValueFromText(this, e); - } - - #endregion VALUE FROM TEXT - - protected override void OnPreviewKeyDown(KeyEventArgs e) - { - if ((e.ImeProcessedKey != Key.None) && (!this.IsInIMEComposition)) - { - // Start of an IME Composition. Cache all the critical infos. - this.StartIMEComposition(); - } - - base.OnPreviewKeyDown(e); - } - - protected override void OnGotFocus(RoutedEventArgs e) - { - base.OnGotFocus(e); - - this.RefreshCurrentText(true); - } - - protected override void OnLostFocus(RoutedEventArgs e) - { - base.OnLostFocus(e); - - this.RefreshCurrentText(true); - } - - protected override void OnTextInput(TextCompositionEventArgs e) - { - if (this.IsInIMEComposition) - this.EndIMEComposition(); - - base.OnTextInput(e); - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - protected virtual void ValidateValue(object value) - { - if (value == null) - return; - - Type validatingType = this.ValueDataType; - if (validatingType.IsGenericType && validatingType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) - { - NullableConverter nullableConverter = new NullableConverter(validatingType); - validatingType = nullableConverter.UnderlyingType; - } - - if (validatingType == null) - throw new InvalidOperationException("An attempt was made to set a value when the ValueDataType property is null."); - - if ((value != DBNull.Value) && (value.GetType() != validatingType)) - throw new ArgumentException("The value is not of type " + validatingType.Name + ".", "Value"); - - this.ValidateValueInRange(this.MinValue, this.MaxValue, value); - } - - internal static bool IsNumericType(Type type) - { - if (type == null) - return false; - - if (type.IsValueType) - { - if ((type == typeof(int)) || (type == typeof(double)) || (type == typeof(decimal)) - || (type == typeof(float)) || (type == typeof(short)) || (type == typeof(long)) - || (type == typeof(ushort)) || (type == typeof(uint)) || (type == typeof(ulong)) - || (type == typeof(byte)) - ) - { - return true; - } - } - - return false; - } - - internal void StartIMEComposition() - { - Debug.Assert(m_imePreCompositionCachedTextInfo == null, "EndIMEComposition should have been called before another IME Composition starts."); - - m_imePreCompositionCachedTextInfo = new CachedTextInfo(this); - } - - internal void EndIMEComposition() - { - CachedTextInfo cachedTextInfo = m_imePreCompositionCachedTextInfo.Clone() as CachedTextInfo; - m_imePreCompositionCachedTextInfo = null; - - this.OnIMECompositionEnded(cachedTextInfo); - } - - internal virtual void OnIMECompositionEnded(CachedTextInfo cachedTextInfo) - { - } - - internal virtual void RefreshConversionHelpers() - { - } - - internal IFormatProvider GetActiveFormatProvider() - { - IFormatProvider formatProvider = this.FormatProvider; - - if (formatProvider != null) - return formatProvider; - - return CultureInfo.CurrentCulture; - } - - internal CultureInfo GetCultureInfo() - { - CultureInfo cultureInfo = this.GetActiveFormatProvider() as CultureInfo; - - if (cultureInfo != null) - return cultureInfo; - - return CultureInfo.CurrentCulture; - } - - internal virtual string GetCurrentText() - { - return this.Text; - } - - internal virtual string GetParsableText() - { - return this.Text; - } - - internal void ForceText(string text, bool preserveCaret) - { - this.IsForcingText = true; - try - { - int oldCaretIndex = this.CaretIndex; - - this.Text = text; - - if ((preserveCaret) && (this.IsLoaded)) - { - try - { - this.SelectionStart = oldCaretIndex; - } - catch (NullReferenceException) - { - } - } - } - finally - { - this.IsForcingText = false; - } - } - - internal bool IsValueNull(object value) - { - if ((value == null) || (value == DBNull.Value)) - return true; - - Type type = this.ValueDataType; - if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) - { - NullableConverter nullableConverter = new NullableConverter(type); - type = nullableConverter.UnderlyingType; - } - - if (value.GetType() != type) - value = System.Convert.ChangeType(value, type); - - object nullValue = this.NullValue; - - if (nullValue == null) - return false; - - if (nullValue.GetType() != type) - nullValue = System.Convert.ChangeType(nullValue, type); - - return nullValue.Equals(value); - } - - internal void ForceValue(object value) - { - this.IsForcingValue = true; - try - { - this.Value = value; - } - finally - { - this.IsForcingValue = false; - } - } - - internal void RefreshCurrentText(bool preserveCurrentCaretPosition) - { - string displayText = this.GetCurrentText(); - - if (!string.Equals(displayText, this.Text)) - this.ForceText(displayText, preserveCurrentCaretPosition); - } - - internal void RefreshValue() - { - if ((this.IsForcingValue) || (this.ValueDataType == null) || (this.IsInIMEComposition)) - return; - - object value; - bool hasParsingError; - - if (this.IsTextReadyToBeParsed) - { - string parsableText = this.GetParsableText(); - - value = this.GetValueFromText(parsableText, out hasParsingError); - - if (this.IsValueNull(value)) - value = this.NullValue; - } - else - { - // We don't consider empty text as a parsing error. - hasParsingError = !this.GetIsEditTextEmpty(); - value = this.NullValue; - } - - this.SetHasParsingError(hasParsingError); - - bool hasValidationError = hasParsingError; - try - { - this.ValidateValue(value); - - this.SetIsValueOutOfRange(false); - } - catch (Exception exception) - { - hasValidationError = true; - - if (this.BeepOnError) - { - System.Media.SystemSounds.Beep.Play(); - } - - if (exception is ArgumentOutOfRangeException) - this.SetIsValueOutOfRange(true); - - value = this.NullValue; - } - - if (!object.Equals(value, this.Value)) - this.ForceValue(value); - - this.SetHasValidationError(hasValidationError); - } - - internal virtual bool GetIsEditTextEmpty() - { - return this.Text == string.Empty; - } - - private static object ConvertValueToDataType(object value, Type type) - { - // We use InvariantCulture instead of the active format provider since the FormatProvider is only - // used when the source type is String. When we are converting from a string, we are - // actually converting a value from XAML. Therefore, if the string will have a period as a - // decimal separator. If we were using the active format provider, we could end up expecting a coma - // as the decimal separator and the ChangeType method would throw. - if (type == null) - return null; - - if (((value != null) && (value != DBNull.Value)) - && (value.GetType() != type)) - { - return ChangeTypeHelper.ChangeType(value, type, CultureInfo.InvariantCulture); - } - - return value; - } - - private void CanEnterLineBreak(object sender, CanExecuteRoutedEventArgs e) - { - e.CanExecute = false; - e.Handled = true; - } - - private void CanEnterParagraphBreak(object sender, CanExecuteRoutedEventArgs e) - { - e.CanExecute = false; - e.Handled = true; - } - - private void ValidateValueInRange(object minValue, object maxValue, object value) - { - if (this.IsValueNull(value)) - return; - - Type type = this.ValueDataType; - if (type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) - { - NullableConverter nullableConverter = new NullableConverter(type); - type = nullableConverter.UnderlyingType; - } - - if (value.GetType() != type) - value = System.Convert.ChangeType(value, type); - - // Validate the value against the range. - if (minValue != null) - { - IComparable minValueComparable = (IComparable)minValue; - - if ((maxValue != null) && (minValueComparable.CompareTo(maxValue) > 0)) - throw new ArgumentOutOfRangeException("minValue", "MaxValue must be greater than MinValue."); - - if (minValueComparable.CompareTo(value) > 0) - throw new ArgumentOutOfRangeException("minValue", "Value must be greater than MinValue."); - } - - if (maxValue != null) - { - IComparable maxValueComparable = (IComparable)maxValue; - - if (maxValueComparable.CompareTo(value) < 0) - throw new ArgumentOutOfRangeException("maxValue", "Value must be less than MaxValue."); - } - } - - #region ISupportInitialize - - protected override void OnInitialized(EventArgs e) - { - this.IsFinalizingInitialization = true; - try - { - this.CoerceValue(ValueRangeTextBox.ValueDataTypeProperty); - - this.IsNumericValueDataType = ValueRangeTextBox.IsNumericType(this.ValueDataType); - this.RefreshConversionHelpers(); - - this.CoerceValue(ValueRangeTextBox.MinValueProperty); - this.CoerceValue(ValueRangeTextBox.MaxValueProperty); - - this.CoerceValue(ValueRangeTextBox.ValueProperty); - - this.CoerceValue(ValueRangeTextBox.NullValueProperty); - - this.CoerceValue(ValueRangeTextBox.TextProperty); - } - catch (Exception exception) - { - throw new InvalidOperationException("Initialization of the ValueRangeTextBox failed.", exception); - } - finally - { - this.IsFinalizingInitialization = false; - } - - base.OnInitialized(e); - } - - #endregion ISupportInitialize - - private BitVector32 m_flags; - private CachedTextInfo m_imePreCompositionCachedTextInfo; - - [Flags] - private enum ValueRangeTextBoxFlags - { - IsFinalizingInitialization = 1, - IsForcingText = 2, - IsForcingValue = 4, - IsInValueChanged = 8, - IsNumericValueDataType = 16 - } -} diff --git a/src/Shared/HandyControl_Shared/Themes/Styles/HandyControls/CommonStyles.xaml b/src/Shared/HandyControl_Shared/Themes/Styles/HandyControls/CommonStyles.xaml index 5021cb67e..b7ec03e3d 100644 --- a/src/Shared/HandyControl_Shared/Themes/Styles/HandyControls/CommonStyles.xaml +++ b/src/Shared/HandyControl_Shared/Themes/Styles/HandyControls/CommonStyles.xaml @@ -190,7 +190,5 @@ - -