簡體   English   中英

獲取C#上的文本框的值

[英]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模式下將TextBoxText屬性綁定,並將UpdateSourceTrigger設置為PropertyChanged到一個public string屬性,該屬性支持視圖( UserControl或包含TextBox Window )的DataContext (通常為ViewModel )中的更改通知。

一旦這樣做,您就可以在每次更改TextBox文本時(每次按下一個鍵)在ViewModel調用一個方法,並在那里進行TextBox值驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM