让用户输入一个正确格式的URL的最好方法?正确、格式、方法、用户

2023-09-03 05:57:04 作者:埘間の誋憶

我创建使用MVVM一个对话框,提示用户在键入一个http:// URL到KML文件。 确定按钮,需要启用时,URL是正确的格式,它需要被禁用时,该URL的格式不正确。

I am creating a dialog using MVVM which prompts the user to type in an http:// URL to a KML file. The "OK" button needs to be enabled when the URL is in the correct format, and it needs to be disabled when the URL is in an incorrect format.

目前的按钮被绑定到一个ICommand的,而对于CanExecute()的逻辑是这样的:

Right now the button is bound to an ICommand, and the logic for CanExecute() looks like this:

return !string.IsNullOrEmpty(CustomUrl);

该命令的CanExecuteChanged事件引发对每一个按键,到目前为止,它的工作好。

The command's CanExecuteChanged event is raised on every keystroke, and so far it's working well.

现在我想做的实际验证了一点点。我知道这样做的唯一方法如下:

Now I want to do a little bit of actual validation. The only way I know to do that is as follows:

try
{
    var uri = new Uri(CustomUrl);
}
catch (UriFormatException)
{
    return false;
}

return true;

这是没有布埃诺,特别是因为确认是发生在每一个按键。我可以使它这样,当用户点击OK按钮的URI进行了验证,但我宁愿不要。有没有更好的方式来验证URI除了捕获异常?

That's no bueno, especially since the validation is happening on each keystroke. I could make it so that the URI is validated when the user hits the OK button, but I'd rather not. Is there a better way to validate the URI other than catching exceptions?

推荐答案

是 - 你可以使用静态方法Uri.IsWellFormedUriString此

Yes - you can use the static method Uri.IsWellFormedUriString for this

return Uri.IsWellFormedUriString (CustomUrl, UriKind.Absolute);