在c#上获取文本框的值

M_M*_*M_M 1 c# wpf textbox

我正在研究一个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;
        }


    }
Run Code Online (Sandbox Code Playgroud)

它还强调了e.KeyCode和e.KeyNumPad0 ....我该怎么办?

Bra*_*NET 5

这不是在WPF中处理此问题的正确方法.

获取值非常简单,只需绑定到View模型上的某些内容:

<TextBox Text="{Binding Path=MyTextValue}"/>
Run Code Online (Sandbox Code Playgroud)

要在每次更改字符时更新它,请设置UpdateSourceTrigger:

<TextBox Text="{Binding Path=MyTextValue, UpdateSourceTrigger=OnPropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)

由于看起来您正在进行验证,我建议您查看有关WPF验证的MSDN文章:绑定验证

你应该(几乎)不必在WPF中捕获实际的击键/按键,除非你正在编写游戏或类似的东西.

这是一个关于StackOverflow的问题也可以提供帮助:WPF TextBox验证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");
      }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的代码隐藏中:

public partial class MainWindow
{
    public MainWindow()
    {
         InitializeComponent();
         DataContext = new MyViewModel();
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该足以让你开始(与XAML一起).如果您有任何疑问,请告诉我!