Opening urls from xaml

I generally use Xamarin Forms to build apps. I’m currently working on a new project and using all the new greatness from Prism. One of those great features is Xaml Navigation. This is a fancy markup extension which allows you to navigate to another page in your app without implementing anything in your view models! It’s super terse and it works with xaml hot reload!

Before markup extensions

View:

<Button Text="My Account" Command="{Binding MyAccountCommand}"/>

ViewModel:

public DelegateCommand MyAccountCommand => new DelegateCommand(() => NavigationService.NavigateTo('MyAccountPage'));

After markup extensions

View (Look ma’, no ViewModel):

<Button Text="My Account" Command="{prism:NavigateTo 'MyAccountPage')"/>

How about urls?

Inspired by this, I set out to build my own xaml markup extension for opening urls in the system browser.

Before markup extensions

View:

<Button Text="Microsoft Learn" Command="{Binding MicrosoftLearnCommand}"/>

ViewModel:

public DelegateCommand MyAccountCommand => new DelegateCommand(() => Launcher.OpenAsync("https://docs.microsoft.com/en-ca/learn/"));

After markup extensions

View (I don’t have another quip for the lack of a ViewModel):

<Button Text="Microsoft Learn" Command="{extensions:OpenBrowser 'https://docs.microsoft.com/en-ca/learn/'}"/>

or use a binding:

<Button Text="Microsoft Learn" Command="{extensions:OpenBrowser}" CommandParameter="{Binding MicrosoftLearnUrl}"/>
xaml markup extensions…they’re magic

The Implementation

Check out my XamlOpenUrl sample xaml markup extension code on github and let me know your thoughts!

Leave a Reply

Your email address will not be published.