2013-04-29 58 views
0

我用TextChangedEventArgs動態創建了一個文本框來限制文本框只輸入數字和小數點。 以下是在C#中wpf屬性代替c中的e.keychar#

const char Delete = (char)8; 
if (Char.IsDigit(e.KeyChar)) 
{ 
    e.Handled = false; 
} 
else if (e.KeyChar == Delete) 
{ 
    e.Handled = false; 
} 
else if (e.KeyChar == '.') 
{ 
    if (!(amt.Text.Contains("."))) 
     e.Handled = false; 
    else 
    { 
     e.Handled = true; 
    } 
} 
else 
{ 
    e.Handled = true; 
} 

的代碼,但我不能在WPF使用。

我試圖用e.key或e.Text更改代碼。但這兩個都不可用。它顯示以下錯誤是否缺少程序集或指令。

請任何人都幫助我。

+0

同樣,您應該學習MVVM並停止嘗試在過程代碼中創建整個UI。這就是XAML的用途。 WPF和所有其他基於XAML的框架與古代傳統框架有着根本的不同,需要不同的思維模式。 – 2013-04-29 14:29:20

+0

[取消WPF文本框更改事件]的可能重複(http://stackoverflow.com/questions/335129/cancelling-a-wpf-textbox-changed-event) – 2013-04-29 17:38:20

回答

2
// one solution for filtering characters in a textbox.  
    // this is the PreviewKeyDown handler for a textbox named tbNumerical 
    // Need to add logic for cancelling repeated decimal point and minus sign 
    // or possible notation like 1.23e2 == 123 
    private void tbNumerical_PreviewKeyDown(object sender, KeyEventArgs e) 
    { 
     System.Windows.Input.Key k = e.Key; 

     // to see the key enums displayed, use a textbox or label 
     // someTextBox.Text = k.ToString(); 

     // filter out control keys, not all are used, add more as needed 
     bool controlKeyIsDown = Keyboard.IsKeyDown(Key.LeftShift);  

     if (!controlKeyIsDown && 
      Key.D0 <= k && k <= Key.D9 || 
      Key.NumPad0 <= k && k <= Key.NumPad9 || 
      k == Key.OemMinus || k == Key.Subtract || 
      k == Key.Decimal || k == Key.OemPeriod) // or OemComma for european decimal point 

     else 
     { 
      e.Handled = true; 

      // just a little sound effect for wrong key pressed 
      System.Media.SystemSound ss = System.Media.SystemSounds.Beep; 
      ss.Play(); 

     } 
    }