Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 输入验证Silverlight_C#_Silverlight_Xaml - Fatal编程技术网

C# 输入验证Silverlight

C# 输入验证Silverlight,c#,silverlight,xaml,C#,Silverlight,Xaml,我有一个未绑定的文本框 <TextBox x:Name="inputBox" Grid.Column="1" Grid.Row="1" /> 文本框仅接受数字(双倍)并在框中写入其他内容(字母或符号)后立即显示警告 在TextChanged事件中,我根据输入的值进行一些计算,并将其显示在TextBlock中,因此我需要一些方法来验证输入是否是用户在框中写入的数字,但我很难找到一个好的方法 有什么想法吗?我以前使用的是一个正则表达式,不允许使用非数字字符。也许这是可以被改编的

我有一个未绑定的文本框

<TextBox x:Name="inputBox" Grid.Column="1" Grid.Row="1"  />

文本框仅接受数字(双倍)并在框中写入其他内容(字母或符号)后立即显示警告

在TextChanged事件中,我根据输入的值进行一些计算,并将其显示在TextBlock中,因此我需要一些方法来验证输入是否是用户在框中写入的数字,但我很难找到一个好的方法


有什么想法吗?

我以前使用的是一个正则表达式,不允许使用非数字字符。也许这是可以被改编的

我的代码是为服务器上的端口编写的,因此只需要数字,但添加端口应该很简单。对于双打(我认为“[^0-9\.]”应该可以,但正则表达式并不是我特别擅长的:-)


也许最好使用
绑定
值转换器
来更新TextBlock的内容。在这种情况下,您可以在转换器内对数值进行验证。

这是何时使用行为的另一个示例

public class TextBoxValidator : Behavior<TextBox>
{
  protected override void OnAttached()
  {
    AssociatedObject.TextChanged += new TextChanged(OnTextChanged);
  }

  private void OnTextChanged(object sender, TextChangedEventArgs e)
  {
    // Here you could add the code shown above by Firedragon or you could
    // just use int.TryParse to see if the number if valid.
    // You could also expose a Regex property on the behavior to allow lots of
    // types of validation
  }
}
公共类TextBoxValidator:行为
{
受保护的覆盖无效附加()
{
AssociatedObject.TextChanged+=新的TextChanged(OnTextChanged);
}
私有void OnTextChanged(对象发送方,textchangedventargs e)
{
//在这里,您可以添加上面Firedragon显示的代码,也可以
//只需使用int.TryParse查看该数字是否有效。
//您还可以在行为上公开一个Regex属性,以允许大量
//验证类型
}
}
您没有真正解释当用户输入无效值时要采取的操作

public class TextBoxValidator : Behavior<TextBox>
{
  protected override void OnAttached()
  {
    AssociatedObject.TextChanged += new TextChanged(OnTextChanged);
  }

  private void OnTextChanged(object sender, TextChangedEventArgs e)
  {
    // Here you could add the code shown above by Firedragon or you could
    // just use int.TryParse to see if the number if valid.
    // You could also expose a Regex property on the behavior to allow lots of
    // types of validation
  }
}