Home > Software design >  Hyperlink button in xamarin forms
Hyperlink button in xamarin forms

Time:10-19

I am making an app where you tap on a button and it opens a certain webpage. I'm quite new to app development. There will be multiple buttons on the page with different links (gotten from a database of links). So there would have to be some way of making a general method that accepts a link from the xaml page, if this is at all possible. What is the best way of opening a link like this? Any help is greatly appreciated

This is the current xaml code for the tiny form

<StackLayout Orientation="Horizontal">
 <StackLayout Orientation="Vertical">
  <Label Text="Link 1" TextColor="{StaticResource Text}" FontSize="18" FontAttributes="Bold" x:Name="label"/>
  <StackLayout Orientation="Horizontal">
   <Label Text=" 85" TextColor="{StaticResource Text}" FontSize="18"/>
   <Label Text=" /-12" TextColor="{StaticResource Text}" FontSize="18"/>
   </StackLayout>
 </StackLayout>
 <Button Margin="0,10,0,0" Text="Open Link" BackgroundColor="{StaticResource Primary}" TextColor="{StaticResource Accent}" FontSize="13" Clicked="OpenBrowser"/>
</StackLayout>

This is the current OpenBrowser code in xaml.cs

public async Task OpenBrowserAsync()
        {
            await Browser.OpenAsync("https://www.google.com");
        }

private void OpenBrowser(object sender, EventArgs e)
        {
            _ = OpenBrowserAsync();
        }

CodePudding user response:

you can embed the url in the ClassId property

<Button Text="Open Link" Clicked="OpenBrowser" ClassId="http://www.google.com" ... />

then in your handler

private async void OpenBrowser(object sender, EventArgs e)
{
   var button = (Button)sender;
   var url = button.ClassId;

   await Browser.OpenAsync(url);
}
  • Related