Page 1 of 1

[SOLVED] Open link in code behind

Posted: Thu Jan 04, 2018 6:19 am
by Greenman1805
I tried to open a html link like this:
private void TextBlock_PointerPressed(object sender, PointerRoutedEventArgs e)
{
HtmlPresenter1.Html = " < meta http - equiv = "refresh" content = "5; URL = https://mylink.com/" >";
}

but it says that HtmlPresenter1 isn't available. I also tried "this.Html..." but it didn't work, so how is this possible? :roll:

Re: Open link in code behind

Posted: Thu Jan 04, 2018 6:37 am
by TaterJuice
What I've done is create a HyperlinkButton, set the NavigationUri property to "google.com" then invoke the OnClick event using Reflection.

Try this:

XAML:

Code: Select all

<Page
    x:Class="MyProject.Pages.ButtonClickPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyProject.Pages">
    <StackPanel>
        <Button
            Content="Go to Google"
            Click="Button_Click" />
    </StackPanel>
</Page>


Code Behind:

Code: Select all

using System;
using System.Reflection;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace MyProject.Pages
{
    public partial class ButtonClickPage : Page
    {
        public ButtonClickPage() { InitializeComponent(); }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var linkButton = new HyperlinkButton();
            linkButton.NavigateUri = new Uri("http://www.google.com", UriKind.RelativeOrAbsolute);
            typeof(ButtonBase).GetMethod("OnClick", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(linkButton, new object[0]);
        }
    }
}

Re: Open link in code behind

Posted: Thu Jan 04, 2018 8:11 am
by Greenman1805
Thanks! I will try this.

Re: Open link in code behind

Posted: Fri Jan 05, 2018 5:18 am
by JS-Support @Userware
Hi,

To open link in code behind, you can also use the following code:

Code: Select all

HtmlPage.Window.Navigate(new Uri(@"https://mylink.com/"), "_blank");


Please note that the browser may require that this code is initiated by a user action, such as a click or another event.

Regards,
JS-Support

Re: Open link in code behind

Posted: Fri Jan 05, 2018 10:47 am
by Greenman1805
JS-Support wrote:Hi,

To open link in code behind, you can also use the following code:

Code: Select all

HtmlPage.Window.Navigate(new Uri(@"https://mylink.com/"), "_blank");


Please note that the browser may require that this code is initiated by a user action, such as a click or another event.

Regards,
JS-Support


Works too! Thanks!