2013-04-29 67 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(); 

     } 
    }