1

I'm working on a wpf app and i want to get the value of textbox i want to use KeyDown & KeyPress to check if the text is a numeric value but when i write KeyPress the compilator underlined the proprity so i can't use it .

private void sb_KeyDown_1(object sender, System.Windows.Input.KeyEventArgs e)
    {
        nonNumberEntered = false;

        // Determine whether the keystroke is a number from the top of the keyboard.
        if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
        {
            // Determine whether the keystroke is a number from the keypad.
            if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
            {
                // Determine whether the keystroke is a backspace.
                if (e.KeyCode != Keys.Back)
                {
                    // A non-numerical keystroke was pressed.
                    // Set the flag to true and evaluate in KeyPress event.
                    nonNumberEntered = true;
                }
            }
        }
        //If shift key was pressed, it's not a number.
        if (Control.ModifierKeys == Keys.Shift)
        {
            nonNumberEntered = true;
        }


    }

and it underlined also e.KeyCode and e.KeyNumPad0 .... what should i do ?

M_M
  • 491
  • 2
  • 10
  • 22
  • When your mouse is over the underlined code you have an error message in the tool tip. What it says? – Dmitry Apr 17 '14 at 22:51
  • The question title seems misleading. Do you want to know how to check if pressed key is numeric, or how to get value of textbox? Related question : [How do I get a TextBox to only accept numeric input in WPF?](http://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf) – har07 Apr 17 '14 at 23:31

2 Answers2

6

This isn't the right way to handle this in WPF.

Getting the value is simple enough, you just bind to something on your View Model:

<TextBox Text="{Binding Path=MyTextValue}"/>

To get it to update on every character change, set the UpdateSourceTrigger:

<TextBox Text="{Binding Path=MyTextValue, UpdateSourceTrigger=OnPropertyChanged}"/>

Since it looks like you are doing validation, I would suggest looking at the MSDN article on Validation in WPF: Binding Validation

You should (almost) never have to capture actual key-strokes/presses in WPF unless you are writing a game or something similar.

Here is a question on StackOverflow that could also help: WPF TextBox Validation C#

Since you clearly aren't set up for MVVM yet, here is some code you will need:

public class MyViewModel : INotifyPropertyChanged
{
   //Standard INotifyPropertyChanged implementation, pick your favorite

   private String myTextValue;
   public String MyTextValue
   {
      get { return myTextValue; }
      set
      {
          myTextValue = vaule;
          OnPropertyChanged("MyTextValue");
      }
}

Then in your codebehind:

public partial class MainWindow
{
    public MainWindow()
    {
         InitializeComponent();
         DataContext = new MyViewModel();
    }
}

That should be more than enough to get you started (along with the XAML). Let me know if you have any questions!

Community
  • 1
  • 1
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • How can i get the value without using a button ? – M_M Apr 17 '14 at 22:58
  • 1
    Where did I mention using a button? You don't need a button! – BradleyDotNET Apr 17 '14 at 23:00
  • Ok but what will be the proprety that i have to use to get the text – M_M Apr 17 '14 at 23:02
  • In my example, the String property called "MyTextValue" on your view model will have the value in it (automatiaclly!). Thats the beauty of the binding system. Note that this isn't true in Windows 8 apps, you have to set the Mode to "TwoWay" ("TwoWay" is the default in WPF). – BradleyDotNET Apr 17 '14 at 23:03
  • Ok then i don't need to have a method to get the text ? – M_M Apr 17 '14 at 23:04
  • Exactly! Unless you count the getter of the property as a method (which it technically is). – BradleyDotNET Apr 17 '14 at 23:05
  • The validation will require some sort of method (see the included links) but just getting the value is easy! – BradleyDotNET Apr 17 '14 at 23:06
  • Ok i guess i should make a method because i need to check if the value is an numeric value ! what should i put to replace KEyDown ? if you can see what i'm asking about ! i mean on the XAML COde – M_M Apr 17 '14 at 23:07
  • Let me start over. Using the code-behind (especially like that) is NOT how WPF is intended to be used. First things first, do you have a view model? If not, please create a class called something like "MyViewModel" and set the data context property of your XAML window to it (probably in the code-behind constructor). Then, create a public String property called "MyTextValue" in it. With the XAML I gave, edits to the UI will be automatically reflected in this property (testable by setting a breakpoint or binding something else to it, like a TextBlock). – BradleyDotNET Apr 17 '14 at 23:08
  • here what i what i have in XAML Code – M_M Apr 17 '14 at 23:11
  • Well, you are missing the provided binding for starters. Please set this up with standard MVVM (the way WPF was meant to be :) ) and look at the code, XAML, and links I provided. Your code is fast going down a rabbit hole you DONT want to be in. As an aside, this is a very WinForms way of approaching this. A common fallacy among new WPF developers is that they try to do thing the same way as in WinForms. WPF is not WinForms, they are set up completely differently. Trying to do it the same way is asking for disaster. – BradleyDotNET Apr 17 '14 at 23:25
1

Bind the Text property of your TextBox in a TwoWay mode and with UpdateSourceTrigger set to PropertyChanged to a public string property supporting change notification in the DataContext (typically a ViewModel) of your view (UserControl or Window containing your TextBox).

Once you do that you'll be able to call a method in your ViewModel every time the TextBox text is changed (every time a key is pressed) and do your TextBox value validation there.

Dean Kuga
  • 11,878
  • 8
  • 54
  • 108