[英]Get the value of the textbox on c#
我正在使用wpf应用程序,我想获取文本框的值,我想使用KeyDown和KeyPress来检查文本是否为数字值,但是当我编写KeyPress时,编译器在属性上加了下划线,所以我不能使用它。
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;
}
}
它也强调了e.KeyCode和e.KeyNumPad0 ....我该怎么办?
这不是在WPF中处理此问题的正确方法。
获得值非常简单,您只需绑定到View模型上的某个对象即可:
<TextBox Text="{Binding Path=MyTextValue}"/>
要使其在每次字符更改时都进行更新,请设置UpdateSourceTrigger:
<TextBox Text="{Binding Path=MyTextValue, UpdateSourceTrigger=OnPropertyChanged}"/>
由于您似乎正在执行验证,因此建议您查看有关WPF中的验证 : 绑定验证的MSDN文章。
除非您正在编写游戏或类似的东西,否则您几乎(永远)不必在WPF中捕获实际的击键/按键。
这是一个有关StackOverflow的问题,该问题也可能会有所帮助: WPF文本框验证C#
由于您显然尚未设置MVVM,因此需要以下代码:
public class MyViewModel : INotifyPropertyChanged
{
//Standard INotifyPropertyChanged implementation, pick your favorite
private String myTextValue;
public String MyTextValue
{
get { return myTextValue; }
set
{
myTextValue = vaule;
OnPropertyChanged("MyTextValue");
}
}
然后在您的代码背后:
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = new MyViewModel();
}
}
这足以使您入门(以及XAML)。 如果您有任何疑问,请告诉我!
在TwoWay
模式下将TextBox
的Text
属性绑定,并将UpdateSourceTrigger
设置为PropertyChanged
到一个public string
属性,该属性支持视图( UserControl
或包含TextBox
Window
)的DataContext
(通常为ViewModel
)中的更改通知。
一旦这样做,您就可以在每次更改TextBox
文本时(每次按下一个键)在ViewModel
调用一个方法,并在那里进行TextBox
值验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.