C# 为web浏览器文本框编程?

C# 为web浏览器文本框编程?,c#,visual-studio-2010,windows-phone-7,C#,Visual Studio 2010,Windows Phone 7,文本框将“http://”添加到用户输入的内容中(例如“google.com”变为“http://google.com),但如果用户在其网站之前输入“http://”,则会出现错误 这是我的代码: private void bargo_Click(object sender, RoutedEventArgs e) { Uri targetUri = new Uri(System.String.Format("http://{0}", bar.Text));

文本框将“http://”添加到用户输入的内容中(例如“google.com”变为“http://google.com),但如果用户在其网站之前输入“http://”,则会出现错误

这是我的代码:

     private void bargo_Click(object sender, RoutedEventArgs e)
    {
        Uri targetUri = new Uri(System.String.Format("http://{0}", bar.Text));
        web.Navigate(targetUri);

    }

您可以测试bar.text是否已以http://开头,如下所示:

    private void bargo_Click(object sender, RoutedEventArgs e)
    {
        string url = bar.Text;
        if (!url.StartsWith("http://"))
        {
            url = "http://" + url;
        }
        web.Navigate(new Uri(url);
    }
如果用户输入“https://”或“ftp://”(或gopher://,irc://,ircs://,ftp://,news://,nntp://,worldwind://,telnet://,svn://,git://,mms://),此方法仍将添加“http://”,并失败

更好的解决方案是将字符串传递到web.Navigate()而不是uri。当您传入字符串时,WebBrowser控件会像浏览器一样自动添加http://

    private void bargo_Click(object sender, RoutedEventArgs e)
    {
        web.Navigate(bar.Text);
    }
编辑:适用于Windows Phone 7

    private void bargo_Click(object sender, RoutedEventArgs e)
    {
        web.NavigateToString(bar.Text);
    }

因此,在输入上测试“http://”,要么删除它,要么不添加它。问题是什么?
如果(!bar.Text.Contains(“http:/”)
?单击go按钮后,如何使文本框失去焦点?您认为必须这样做吗?这和你发布的代码有什么关系?或者您收到的任何错误?出于某些奇怪的原因,web.navigate(bar.text)无法与windows phone一起使用。我错过了您使用windows phone的消息。Try:web.NavigateToString(bar.Text);
var culture = System.Globalization.CultureInfo.InvariantCulture.CompareInfo;
if (culture .IsPrefix(textbox.Text, "http://") == false)
    textbox.Text = "http://" + textbox.Text;
var regex = new Regex(@"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$");
if (regex.IsMatch(textbox.Text))
{
   //Your logic here
}