我正在开发一个 uwp 桌面应用程序,它必须验证在文本框中输入的值,以便它们是双精度类型。如果不是,则焦点必须保留在当前控件上。我试过下面的代码。
private async void tbxValue_LosingFocus(UIElement sender, LosingFocusEventArgs args)
{
try
{
double dbl = Convert.ToDouble(tbxValue.Text);
}
catch (Exception ex)
{
args.Cancel = true;
MessageDialog msgDlg = new MessageDialog(resourceLoader.GetString("MsgDlgValueError"));
await msgDlg.ShowAsync();
}
}
编辑
感谢Flydog57的评论,我找到了解决方案
private async void myTextBox_LosingFocus(UIElement sender, LosingFocusEventArgs args)
{
if(!double.TryParse(((TextBox)sender).Text, out double dbl))
{
bool bolCancel = args.TryCancel();
if(bolCancel)
{
MessageDialog msgDlg = new MessageDialog(resourceLoader.GetString("MsgDlgValueError"));
await msgDlg.ShowAsync();
}
}
}
首先,如果您需要验证输入值,您可以处理 TextBox.TextChanged 事件。然后检查双精度值。
但是有一点需要记住。如果您想使用其他控件(如
MessageDialog
或 ContentDialog
或 PopUP
)弹出值错误消息,则 TextBox
肯定会失去焦点。这是设计使然。弹出内容将获得焦点。对于其他场景,我们可以处理LostFocus事件并手动设置焦点状态,以防止TextBox
失去焦点。
代码如下所示:
private async void MyBox_TextChanged(object sender, TextChangedEventArgs e)
{
double dbl = 0;
var isDouble= double.TryParse(MyBox.Text, out dbl);
if (!isDouble)
{
MessageDialog msgDlg = new MessageDialog("123123");
await msgDlg.ShowAsync();
}
}
private void MyBox_LostFocus(object sender, RoutedEventArgs e)
{
MyBox.Focus(FocusState.Programmatic);
}
感谢Flydog57的评论,我找到了解决方案
private async void myTextBox_LosingFocus(UIElement sender, LosingFocusEventArgs args)
{
if(!double.TryParse(((TextBox)sender).Text, out double dbl))
{
bool bolCancel = args.TryCancel();
if(bolCancel)
{
MessageDialog msgDlg = new MessageDialog(resourceLoader.GetString("MsgDlgValueError"));
await msgDlg.ShowAsync();
}
}
}