如何在 UWP C# 中单击按钮打开特定的 URL(YouTube 视频)?

How to open a specific URL (a YouTube video) on a button click in UWP C#?

编辑: 我只是检查整个标签是否为空白,而不是标签中的URL,所以它导致总是空白并且总是抛出异常。

我希望能够在用户的默认浏览器中单击按钮打开特定 URL,例如 YouTube 视频、google 搜索等

使用await Windows.System.Launcher.LaunchUriAsync(new Uri(url));时,URL无效,此方法只能打开'normal'个网站,如https://microsoft.com.

有什么方法可以在单击按钮时打开特定的 URL 吗?

代码:

private async void imageTapEvent(object sender, RoutedEventArgs e)
    {
        try
        {
            if (((String)(((Image)sender).Tag)) != "")
                await Windows.System.Launcher.LaunchUriAsync(new Uri(((ImageTag)(((Image)sender).Tag)).url));
        }
        catch (Exception)
        {
            MessageDialog msg = new MessageDialog("The chosen URL is invalid", "Invalid URL");
            await msg.ShowAsync();
    }

标签是 URL 保存为字符串。

Is there any way to open a specific URL in a UWP app?

当然,UWP 有 WebView control that use to render html page, you could give it uri source, then the WebView will render the website in the app. For more detail please refer Web view document

<WebView x:Name="webView1" Source="http://www.contoso.com"/>

更新

您也可以启动默认浏览器来加载 uri,如下所示

private async void Button_Click(object sender, RoutedEventArgs e)
{
    string uriToLaunch = @"https://www.test.com";
    var uri = new Uri(uriToLaunch);

    // Set the option to show a warning
    var options = new Windows.System.LauncherOptions();
    options.TreatAsUntrusted = true;

    // Launch the URI with a warning prompt
    var success = await Windows.System.Launcher.LaunchUriAsync(uri, options);

    if (success)
    {
        // URI launched
    }
    else
    {
        // URI launch failed
    }

}