Determining the Enter key is pressed in a TextBox

前端 未结 5 1325
无人共我
无人共我 2021-02-02 07:08

Consider a XAML TextBox in Win Phone 7.

  

The goal here is that when the user presses the Enter

相关标签:
5条回答
  • 2021-02-02 07:14

    If you are using the emulator, you can also do something like this to detect the enter key from your physical keyboard.

        private void textBox1_KeyUp(object sender, KeyEventArgs e) {
            var isEnterKey =
                e.Key == System.Windows.Input.Key.Enter ||
                e.PlatformKeyCode == 10;
    
            if (isEnterKey) {
                // ...
            }
        }
    
    0 讨论(0)
  • 2021-02-02 07:18

    A straight forward approach for this in a textbox is

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            Debug.WriteLine("Enter");
        }
    }
    
    0 讨论(0)
  • 2021-02-02 07:25

    If you don't want to add any code to your XAML's code behind file and keep your desing clean from MVVM architecture point, you can use the following approach. In your XAML define your command in binding like this:

     <TextBox 
    Text="{Binding Text}" 
    custom:KeyUp.Command="{Binding Path=DataContext.DoCommand, ElementName=root}" />
    

    where KeyUp class:

    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    
    namespace PhoneGuitarTab.Controls
    {
        public static class KeyUp
        {
            private static readonly DependencyProperty KeyUpCommandBehaviorProperty = DependencyProperty.RegisterAttached(
                "KeyUpCommandBehavior",
                typeof(TextBoxCommandBehavior),
                typeof(KeyUp),
                null);
    
    
            /// 
            /// Command to execute on KeyUp event.
            /// 
            public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
                "Command",
                typeof(ICommand),
                typeof(KeyUp),
                new PropertyMetadata(OnSetCommandCallback));
    
            /// 
            /// Command parameter to supply on command execution.
            /// 
            public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached(
                "CommandParameter",
                typeof(object),
                typeof(KeyUp),
                new PropertyMetadata(OnSetCommandParameterCallback));
    
    
            /// 
            /// Sets the  to execute on the KeyUp event.
            /// 
            /// TextBox dependency object to attach command
            /// Command to attach
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
            public static void SetCommand(TextBox textBox, ICommand command)
            {
                textBox.SetValue(CommandProperty, command);
            }
    
            /// 
            /// Retrieves the  attached to the .
            /// 
            /// TextBox containing the Command dependency property
            /// The value of the command attached
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
            public static ICommand GetCommand(TextBox textBox)
            {
                return textBox.GetValue(CommandProperty) as ICommand;
            }
    
            /// 
            /// Sets the value for the CommandParameter attached property on the provided .
            /// 
            /// TextBox to attach CommandParameter
            /// Parameter value to attach
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
            public static void SetCommandParameter(TextBox textBox, object parameter)
            {
                textBox.SetValue(CommandParameterProperty, parameter);
            }
    
            /// 
            /// Gets the value in CommandParameter attached property on the provided 
            /// 
            /// TextBox that has the CommandParameter
            /// The value of the property
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
            public static object GetCommandParameter(TextBox textBox)
            {
                return textBox.GetValue(CommandParameterProperty);
            }
    
            private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
            {
                TextBox textBox = dependencyObject as TextBox;
                if (textBox != null)
                {
                    TextBoxCommandBehavior behavior = GetOrCreateBehavior(textBox);
                    behavior.Command = e.NewValue as ICommand;
                }
            }
    
            private static void OnSetCommandParameterCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
            {
                TextBox textBox = dependencyObject as TextBox;
                if (textBox != null)
                {
                    TextBoxCommandBehavior behavior = GetOrCreateBehavior(textBox);
                    behavior.CommandParameter = e.NewValue;
                }
            }
    
            private static TextBoxCommandBehavior GetOrCreateBehavior(TextBox textBox)
            {
                TextBoxCommandBehavior behavior = textBox.GetValue(KeyUpCommandBehaviorProperty) as TextBoxCommandBehavior;
                if (behavior == null)
                {
                    behavior = new TextBoxCommandBehavior(textBox);
                    textBox.SetValue(KeyUpCommandBehaviorProperty, behavior);
                }
    
                return behavior;
            }
        }
    }

    The class uses additional ones, so I provide them too. TextBoxCommandBehavior class:

    using System;
    using System.Windows.Controls;
    using System.Windows.Input;
    
    namespace PhoneGuitarTab.Controls
    {
        public class TextBoxCommandBehavior : CommandBehaviorBase
        {
            public TextBoxCommandBehavior(TextBox textBoxObject)
                : base(textBoxObject)
            {
                textBoxObject.KeyUp += (s, e) =>
                                           {
                                               string input = (s as TextBox).Text;
                                               //TODO validate user input here
                                               **//ENTER IS PRESSED!**
                                               if ((e.Key == Key.Enter) 
                                                   && (!String.IsNullOrEmpty(input)))
                                               {
                                                   this.CommandParameter = input;
                                                   ExecuteCommand();
                                               }
                                           };
    
            }
        }
    }

    CommandBehaviorBase class:

    using System;
    using System.Windows.Controls;
    using System.Windows.Input;
    
    namespace PhoneGuitarTab.Controls
    {
        /// 
        /// Base behavior to handle connecting a  to a Command.
        /// 
        /// The target object must derive from Control
        /// 
        /// CommandBehaviorBase can be used to provide new behaviors similar to .
        /// 
        public class CommandBehaviorBase
                    where T : Control
        {
            private ICommand command;
            private object commandParameter;
            private readonly WeakReference targetObject;
            private readonly EventHandler commandCanExecuteChangedHandler;
    
    
            /// 
            /// Constructor specifying the target object.
            /// 
            /// The target object the behavior is attached to.
            public CommandBehaviorBase(T targetObject)
            {
                this.targetObject = new WeakReference(targetObject);
                this.commandCanExecuteChangedHandler = new EventHandler(this.CommandCanExecuteChanged);
            }
    
            /// 
            /// Corresponding command to be execute and monitored for 
            /// 
            public ICommand Command
            {
                get { return command; }
                set
                {
                    if (this.command != null)
                    {
                        this.command.CanExecuteChanged -= this.commandCanExecuteChangedHandler;
                    }
    
                    this.command = value;
                    if (this.command != null)
                    {
                        this.command.CanExecuteChanged += this.commandCanExecuteChangedHandler;
                        UpdateEnabledState();
                    }
                }
            }
    
            /// 
            /// The parameter to supply the command during execution
            /// 
            public object CommandParameter
            {
                get { return this.commandParameter; }
                set
                {
                    if (this.commandParameter != value)
                    {
                        this.commandParameter = value;
                        this.UpdateEnabledState();
                    }
                }
            }
    
            /// 
            /// Object to which this behavior is attached.
            /// 
            protected T TargetObject
            {
                get
                {
                    return targetObject.Target as T;
                }
            }
    
    
            /// 
            /// Updates the target object's IsEnabled property based on the commands ability to execute.
            /// 
            protected virtual void UpdateEnabledState()
            {
                if (TargetObject == null)
                {
                    this.Command = null;
                    this.CommandParameter = null;
                }
                else if (this.Command != null)
                {
                    TargetObject.IsEnabled = this.Command.CanExecute(this.CommandParameter);
                }
            }
    
            private void CommandCanExecuteChanged(object sender, EventArgs e)
            {
                this.UpdateEnabledState();
            }
    
            /// 
            /// Executes the command, if it's set, providing the 
            /// 
            protected virtual void ExecuteCommand()
            {
                if (this.Command != null)
                {
                    this.Command.Execute(this.CommandParameter);
                }
            }
        }
    }

    You can find the working example at my open source project (PhoneGuitarTab.Controls project in solution): http://phoneguitartab.codeplex.com

    0 讨论(0)
  • 2021-02-02 07:32

    You'll be looking to implement the KeyDown event specific to that textbox, and checking the KeyEventArgs for the actual Key pressed (and if it matches Key.Enter, do something)

    <TextBox Name="Box" InputScope="Text" KeyDown="Box_KeyDown"></TextBox>
    
    private void Box_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key.Equals(Key.Enter))
        {
            //Do something
        }
    }
    

    Just a note that in the Beta version of the WP7 emulator, although using the software on-screen keyboard detects the Enter key correctly, if you're using the hardware keyboard (activated by pressing Pause/Break), the Enter key seems to come through as Key.Unknown - or at least, it was doing so on my computer...

    0 讨论(0)
  • 2021-02-02 07:34

    Disabling the keyboard

    Was faced with the same problem; the examples above only gives details about how to trap the keyboard press event (which answers the question), but to disable the keyboard, onclick or enter, I just have the focus set to another control altogether.

    Which will result in disabling the keyboard.

    private void txtCodeText_KeyDown(object sender, KeyEventArgs e)
    {
        if(e.Key.Equals(Key.Enter))
        {
            //setting the focus to different control
            btnTransmit.Focus();
        }
    }
    
    0 讨论(0)
提交回复
热议问题