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 ?
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!
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.