在c#上获取文本框的值

时间:2014-04-17 22:44:32

标签: 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;
        }


    }

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

2 个答案:

答案 0 :(得分:5)

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

获取值非常简单,只需绑定到View Model上的内容:

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

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

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

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

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

这是一个关于StackOverflow的问题,也可以提供帮助:WPF TextBox Validation 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一起)。如果您有任何问题,请告诉我们!

答案 1 :(得分:0)

Text TextBox属性绑定到TwoWay模式,将UpdateSourceTrigger设置为PropertyChanged,将public string属性绑定到支持更改的DataContext属性您的观看次数ViewModel(通常为UserControl)的通知(WindowTextBox包含您的ViewModel)。

一旦你这样做,每次TextBox文本发生更改时(每次按下一个键),你都可以在TextBox中调用一个方法并执行你的{{1那里的值验证。

相关问题