Posted on Leave a comment

Unified Blazor UI in the Mobile Blazor Bindings Preview 5

Eilon Lipton

Eilon

I’m excited to announce that today we are releasing the Mobile Blazor Bindings Preview 5 update that adds support for sharing UI between web apps and mobile/desktop apps. You can now use a Razor Class Library (RCL) to build your UI and app logic once and use it in a Blazor Web app and in a Mobile Blazor Bindings app. This release also includes many other improvements, such as support for Shell with Blazor @page routing, SkiaSharp for rich graphics, gesture recognizers, and a whole lot more!

You can build one UI using Blazor Web and host it in a Blazor Server or Blazor Web Assembly app and also in a Mobile Blazor Bindings hybrid app to target Android, iOS, macOS, and Windows:

Image cat tracker options

These are the major new features in the 0.5 Preview 5 release:

  • Build your UI in a Razor Class Library (RCL) and share the same UI between web app and native app, including static assets such as CSS and images (community contribution from Jan-Willem Spuij)
  • Support for Shell with Routing, including the Razor @page directive (community contribution from Lachlan Gordon
  • Support for SkiaSharp graphics (community contribution from Lachlan Gordon
  • Gesture recognizers (tap, swipe, etc.)
  • Dual-screen device support
  • Added FontImageSource, DatePicker, TimePicker
  • Simplified Grid layout syntax
  • Update to Xamarin.Forms 4.8
  • Nightly package feed
  • OSS docs on GitHub
  • And several bug fixes and other small improvements
  • The full list of closed issues is here: https://github.com/xamarin/MobileBlazorBindings/milestone/5?closed=1

Get started

To get started building a Blazor Hybrid app with Experimental Mobile Blazor Bindings preview 5, install the .NET Core 3.1 SDK, have Visual Studio with the Mobile development with .NET (Xamarin.Forms) and ASP.NET and web development workloads installed, and then run the following command:

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.5.50-preview

And then create your first project by running this command:

dotnet new blazorhybrid -o MyHybridApp

Note: For additional information on required software, please check the Getting Started article.

Now open it in Visual Studio and run it on Android, iOS, Windows, or macOS. That’s it! You can find additional docs and tutorials on https://docs.microsoft.com/mobile-blazor-bindings/. We have a new tutorial for building a Razor Class Library and including it in a Blazor Server app as well as targeting Android, iOS, macOS, and Windows platforms.

Upgrade an existing project

To update an existing Mobile Blazor Bindings project please refer to the Migrate Mobile Blazor Bindings From Preview 4 to Preview 5 topic for full details.

Razor Class Library support

Razor Class Libraries are a feature of Razor that enable you to package part of your application’s UI and logic into a reusable library. This library can then be reused in multiple web applications. Now in Mobile Blazor Bindings you can use the same library in a Blazor Hybrid application as part of a mobile or desktop app. The web content is hosted in a Web View, just like any hybrid app content, and it can interact with any native parts of the application, and the reverse is true as well. Previous versions included limited support for RCLs, and this version adds improved support for them, particularly support for serving static assets such as CSS and images, as well as support for JSInterop for interop between JavaScript and .NET code.

Shell navigation

To build a great native experience for your app you can use the Shell control that comes from Xamarin.Forms. Starting with Preview 5 you can author native Blazor pages with the @page "/search/{query}" syntax and integrate them with the Shell’s navigation (such as the Back button) and navigate to them using the new NavigationManager.NavigateToAsync($"/search/{query}") API. Pages can use the navigation manager by injecting it from the DI container as in @inject ShellNavigationManager NavigationManager.

SkiaSharp graphics

SkiaSharp is a popular cross-platform graphics library based on Google’s Skia graphics library. In Preview 5 you can directly use SkiaSharp’s Canvas APIs to render rich high-performance graphics directly in your Mobile Blazor Bindings app.

Here’s what a simple canvas might look like:

<ContentView> <StackLayout Padding="20"> <SKCanvasView OnPaintSurface="PaintSurface"/> </StackLayout>
</ContentView> @code
{ void PaintSurface(SKPaintSurfaceEventArgs e) { var canvas = e.Surface.Canvas; canvas.Clear(SKColors.Green); var paint = new SKPaint { Color = SKColors.SkyBlue, }; canvas.DrawLine(0, 0, 200, 200, paint); }
}

And here’s what a more complex canvas might render as:

SkiaSharp rendering a graph in Mobile Blazor Bindings on iOS

More information

Thank you to contributors

This release had several major contributions from community contributors:

  • Jan-Willem Spuij added support for Razor Class Libraries with static assets. He stayed up late (his time) on calls with me several times and I appreciate his hard work!
  • Lachlan Gordon added support for Shell navigation and SkiaSharp. His patience in playing time-zone ping-pong (Australia vs. USA) is most appreciated and resulted in high quality contributions!

Thanks you to Jan-Willem, Lachlan, and everyone else who contributed to this release!

What’s next? Let us know what you want!

This project relies on your feedback to help shape the future of Blazor for native and hybrid scenarios. Please share your thoughts on this blog post or at the GitHub repo so we can keep the discussion going.

Posted on Leave a comment

Hybrid Blazor apps in the Mobile Blazor Bindings July update

Eilon Lipton

Eilon

I’m excited to announce we are releasing the Mobile Blazor Bindings July update! This release adds support for building Hybrid Blazor apps, which contain both native and web UI.

Hybrid apps are a composition of native and web UI in a single app. With Mobile Blazor Bindings this means you can write the native UI of your app using Blazor, and also create web UI in your app using Blazor. A major advantage of hybrid apps is that the HTML part of the app can reuse content, layout, and styles that are used in a regular web app, while enabling rich native UI to be composed alongside it. You can reuse code, designs, and knowledge, while still taking full advantage of each platform’s unique features. This feature supports Android, iOS, Windows (WPF), and macOS. And it’s all Blazor, C#, .NET, and Visual Studio. Woohoo!

You can mix and match native and web UI in whatever structure makes sense for your app. Here’s a simple example:

Blazor Hybrid app in iOS Simulator

These are the major new features in the 0.4 Preview 4 release:

  • New Hybrid Apps feature enables mixing Blazor native UI components with Blazor web UI components in the same page. This one is HUGE!
  • Hybrid Apps are hosted in a new BlazorWebView component that uses a browser component to contain the web part of the app. No remote or local web server; all your code runs in the app’s process.
  • New blazorhybrid project template that supports Android, iOS, Windows (WPF), and macOS for creating hybrid apps
  • Updated dependencies: Xamarin.Forms 4.7, Xamarin.Essentials 1.5, and other libraries.
  • .NET Core 3.1 SDK is required to use the new preview

How does it work?

In hybrid apps all the code (both for the native UI parts and the web UI parts) runs as .NET code on the device. There is no local or remote web server and no WebAssembly (WASM). The .NET code for the entire app runs in a single process. The native UI components run as the device’s standard UI components (button, label, etc.) and the web UI components are hosted in a browser view (such as WebKit, Chromium, and Edge WebView2). The components can share state using standard .NET patterns, such as event handlers, dependency injection, or anything else you are already using in your apps today.

Get started

To get started building a Blazor Hybrid app with Experimental Mobile Blazor Bindings preview 4, install the .NET Core 3.1 SDK and then run the following command:

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.4.74-preview

And then create your first project by running this command:

dotnet new blazorhybrid -o MyHybridApp

Now open it in Visual Studio and run it on Android, iOS, Windows, or macOS. That’s it! You can find additional docs and tutorials on https://docs.microsoft.com/mobile-blazor-bindings/.

Blazor Hybrid code sample

Here’s the code for an app similar to what was seen at the top of this post. It has native UI and web UI sharing the same app state, running together in the same app process (no web server or HTTP). The native UI uses the new <BlazorWebView> component to specify which web component to load and where to locate static web assets. Blazor does all the work.

This is the main native UI page /Main.razor:

@inject CounterState CounterState <ContentView> <StackLayout> <StackLayout Margin="new Thickness(20)"> <Label Text="@($"You pressed {CounterState.CurrentCount} times")" FontSize="30" /> <Button Text="Increment from native" OnClick="@CounterState.IncrementCount" Padding="10" /> </StackLayout> <BlazorWebView ContentRoot="WebUI/wwwroot" VerticalOptions="LayoutOptions.FillAndExpand"> <FirstBlazorHybridApp.WebUI.App /> </BlazorWebView> </StackLayout>
</ContentView> @code { // initialization code
}

And this is the embedded HTML UI page /WebUI/App.razor:

@inject CounterState CounterState <div style="text-align: center; background-color: lightblue;"> <div> <span style="font-size: 30px; font-weight: bold;"> You pressed @CounterState.CurrentCount times </span> </div> <div> <button style="margin: 20px;" @onclick="ClickMe">Increment from HTML</button> </div>
</div> @code
{ private void ClickMe() { CounterState.IncrementCount(); } // initialization code
}

Upgrade an existing project

To update an existing Mobile Blazor Bindings project please refer to the Migrate Mobile Blazor Bindings From Preview 3 to Preview 4 topic for full details.

More information

Check out last month’s ASP.NET Community Standup where I talked a bit about these new features and did a demo of Blazor hybrid apps (starts at 30:35):

For more information please check out:

Thank you to contributors

This release had several major contributions from Jan-Willem Spuij. Jan-Willem had already built his own BlazorWebView component and kindly helped us get this functionality into the Mobile Blazor Bindings project with many great improvements. Thank you Jan-Willem!

What’s next? Let us know what you want!

This project relies on your feedback to help shape the future of Blazor for native and hybrid scenarios. Please share your thoughts on this blog post or at the GitHub repo so we can keep the discussion going.

Posted on Leave a comment

Announcing Experimental Mobile Blazor Bindings May update

Eilon Lipton

Eilon

It’s been a few months so it’s time for another update of Experimental Mobile Blazor Bindings! This release brings several bug fixes in the areas of CSS styling support, adding XML doc comments to common APIs, and several syntax improvements to common controls.

Here are the major changes in this release:

  • Update to latest native mobile component versions in Xamarin.Forms 4.5 and add doc comments #96, #110, #111
  • Improve Label and Button syntax #87, #27
  • Fix CSS support for iOS apps #109
  • Breaking change: Use space-separated CSS classes instead of comma-separated #100

Get started

To get started with Experimental Mobile Blazor Bindings preview 3, install the .NET Core 3.1 SDK and then run the following command:

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.3.26-preview

And then create your first project by running this command:

dotnet new mobileblazorbindings -o MyApp

That’s it! You can find additional docs and tutorials on https://docs.microsoft.com/mobile-blazor-bindings/.

Upgrade an existing project

To update an existing Mobile Blazor Bindings project please refer to the Migrate Mobile Blazor Bindings From Preview 2 to Preview 3 topic for full details.

Updated components and docs

Because most of the components in Mobile Blazor Bindings are based on Xamarin.Forms native controls, the components have been updated to Xamarin.Forms 4.5. For example, properties such as Image.IsAnimationPlaying and Stepper.StepperPosition are now available. The doc comments that are seen in IntelliSense have also been imported so that you get useful help while coding:

Mobile Blazor Bindings IntelliSense docs tooltip

Improve Label and Button syntax

Because one of the key motivators for building Mobile Blazor Bindings was to have patterns that were more familiar to web developers, the syntax for Label and Button components has been simplified and improved.

In previous versions setting the text for a Label’s Span’s Text or a Button’s Text had to be done via a property setter:

<Button Text="Click me" ... />
...
<Button Text="@("Buy " + @items.Count + " items")" ... />

Starting with Preview 3 you can use this simplified syntax that is more similar to web patterns:

<Button ...>Click me</Button>
...
<Button ...>Buy @items.Count items</Button>

This change applies to Button.Text and Span.Text.

Speaking of Span.Text, a Label with complex formatting used to have many intermediate tags:

<Label FontSize="12"> <FormattedText> <FormattedString> <Spans> <Span Text="This text is large... " FontSize="50" /> <Span Text="and this is plain... " /> <Span Text="and this is green!" TextColor="Color.Green" /> </Spans> </FormattedString> </FormattedText>
</Label>

And starting with Preview 3, the intermediate tags have all been removed:

<Label FontSize="12"> <Span FontSize="50">This text is large... </Span> <Span>and this is plain... </Span> <Span TextColor="Color.Green">and this is green!</Span>
</Label>

CSS improvements

CSS is a great way to style your application while keeping it separate from the layout and behavior. Check out the CSS Styles topic for more information on how to use CSS in your Mobile Blazor Bindings apps.

There are three CSS-related improvements in this release:

  1. The minimum version of Xamarin.Forms is now 4.5, which fixes most CSS issues, such as the ability to use almost all CSS selectors.
  2. A small breaking change was made to use spaces as separators instead of commas when specifying multiple class names (this matches web behavior). See issue #100 for more information.
  3. A bug fix was made to ensure CSS is loaded properly on iOS devices.

More information:

For more information please check out:

Thank you to community blog posts!

If you’d like to learn more, please check out these blog posts from community members:

Thank you!

What’s next? Let us know what you want!

We’re listening to your feedback, which has been both plentiful and helpful! We’re also fixing bugs and adding new features. And you may have seen last week’s announcement for .NET Multi-platform App UI (.NET MAUI). As an experiment, what we find with Mobile Blazor Bindings will feed directly into the Blazor aspects of .NET MAUI so please share with us your thoughts on using Blazor with .NET MAUI on this project’s repo or on .NET MAUI’s GitHub repo.

This project will continue to take shape in large part due to your feedback, so please let us know your thoughts at the GitHub repo.

P.S.: My apologies for the delay in this update. The realities of work-from-home (and stay-at-home parenting) meant that progress was extremely limited. I thank everyone for their patience, understanding, and support. You can always stay up-to-date by going to the GitHub repo and using the latest builds, or reach me on Twitter @original_ejl.

Posted on Leave a comment

Announcing Experimental Mobile Blazor Bindings February update

Eilon Lipton

Eilon

I’m delighted to share an update of Experimental Mobile Blazor Bindings with several new features and fixes. On January 14th we announced the first experimental release of Mobile Blazor Bindings, which enables developers to use familiar web programming patterns to build native mobile apps using C# and .NET for iOS and Android.

Here’s what’s new in this release:

  • New BoxView, CheckBox, ImageButton, ProgressBar, and Slider components
  • Xamarin.Essentials is included in the project template
  • Several properties, events, and other APIs were added to existing components
  • Made it easier to get from a Blazor component reference to the Xamarin.Forms control
  • Several bug fixes, including iOS startup

Get started

To get started with Experimental Mobile Blazor Bindings preview 2, install the .NET Core 3.1 SDK and then run the following command:

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.2.42-preview

And then create your first project by running this command:

dotnet new mobileblazorbindings -o MyApp

That’s it! You can find additional docs and tutorials on https://docs.microsoft.com/mobile-blazor-bindings/.

Upgrade an existing project

To update an existing Mobile Blazor Bindings Preview 1 project to Preview 2 you’ll need to update the Mobile Blazor Bindings NuGet packages to 0.2.42-preview. In each project file (.csproj) update the Microsoft.MobileBlazorBindings package reference’s Version attribute to 0.2.42-preview.

Refer to the Migrate Mobile Blazor Bindings From Preview 1 to Preview 2 topic for full details.

New components

New BoxView, CheckBox, ImageButton, ProgressBar, and Slider components have been added. A picture is worth a thousand words, so here are the new components in action:

New components in Mobile Blazor Bindings preview 2

And instead of a thousand words, here’s the code for that UI page:

<Frame CornerRadius="10" BackgroundColor="Color.LightBlue"> <StackLayout> <Label Text="How much progress have you made?" /> <Slider @bind-Value="progress" /> <Label Text="Your impact:" /> <ProgressBar Progress="EffectiveProgress" /> <StackLayout Orientation="StackOrientation.Horizontal"> <CheckBox @bind-IsChecked="isTwoXProgress" VerticalOptions="LayoutOptions.Center" /> <Label Text="Use 2x impact?" VerticalOptions="LayoutOptions.Center" /> </StackLayout> <BoxView HeightRequest="20" CornerRadius="5" Color="Color.Purple" /> <StackLayout Orientation="StackOrientation.Horizontal" VerticalOptions="LayoutOptions.Center"> <Label Text="Instant completion" VerticalOptions="LayoutOptions.Center" /> <ImageButton Source="@(new FileImageSource { File="CompleteButton.png" })" HeightRequest="64" WidthRequest="64" OnClick="CompleteProgress" VerticalOptions="LayoutOptions.Center" BorderColor="Color.SaddleBrown" BorderWidth="3" /> </StackLayout> </StackLayout> </Frame> @code
{ double progress; bool isTwoXProgress; double EffectiveProgress => isTwoXProgress ? 2d * progress : progress; void CompleteProgress() { progress = 1d; }
}

Xamarin.Essentials is included in the project template

Xamarin.Essentials provides developers with cross-platform APIs for their mobile applications. With these APIs you can make cross-platform calls to get geolocation info, get device status and capabilities, access the clipboard, and much more.

Here’s how to get battery status and location information:

<StackLayout> <StackLayout Orientation="StackOrientation.Horizontal"> <ProgressBar Progress="Battery.ChargeLevel" HeightRequest="20" HorizontalOptions="LayoutOptions.FillAndExpand" /> <Label Text="@($"{Battery.ChargeLevel.ToString("P")}")" /> </StackLayout> <Label Text="@($"🔋 state: {Battery.State.ToString()}")" /> <Label Text="@($"🔋 source: {Battery.PowerSource.ToString()}")" /> <Button Text="Where am I?" OnClick="@WhereAmI" />
</StackLayout> @code
{ async Task WhereAmI() { var location = await Geolocation.GetLocationAsync(new GeolocationRequest(GeolocationAccuracy.Medium)); var locationMessage = $"Lat: {location.Latitude}, Long: {location.Longitude}, Alt: {location.Altitude}"; await Application.Current.MainPage.DisplayAlert("Found me!", locationMessage, "OK"); }
}

More information:

Several properties, events, and other APIs were added to existing components

The set of properties available on the default components in Mobile Blazor Bindings now match the Xamarin.Forms UI controls more closely.

For example:

  • Button events were added: OnPress, OnRelease
  • Button properties were added: FontSize, ImageSource, Padding, and many more
  • Label properties were added: MaxLines, Padding, and many more
  • MenuItem property was added: IsEnabled
  • NavigableElement property was added: class
  • And many more!

Made it easier to get from a Blazor component reference to the Xamarin.Forms control

While most UI work is done directly with the Blazor components, some UI functionality is performed by accessing the Xamarin.Forms control. For example, Xamarin.Forms controls have rich animation capabilities that can be accessed via the control itself, such as rotation, fading, scaling, and translation.

To access the Xamarin.Forms element you need to:

  1. Define a field of the type of the Blazor component. For example: Microsoft.MobileBlazorBindings.Elements.Label counterLabel;
  2. Associate the field with a reference to the Blazor component. For example: <label @ref="counterLabel" …></label>
  3. Access the native control via the NativeControl property. For example: await counterLabel.NativeControl.RelRotateTo(360);

Here’s a full example of how to do a rotation animation every time a button is clicked:

<StackLayout Orientation="StackOrientation.Horizontal" HorizontalOptions="LayoutOptions.Center"> <Button Text="Increment" OnClick="IncrementCount" /> <Label @ref="counterLabel" Text="@("The button was clicked " + count + " times")" FontAttributes="FontAttributes.Bold" VerticalTextAlignment="TextAlignment.Center" /> </StackLayout> @code
{ Microsoft.MobileBlazorBindings.Elements.Label counterLabel; int count; async Task IncrementCount() { count++; var degreesToRotate = ((double)(60 * count)); await counterLabel.NativeControl.RelRotateTo(degreesToRotate); }
}

Learn more in the Xamarin.Forms animation topic.

Bug fixes

This release incorporates several bug fixes, including fixing an iOS startup issue. You can see the full list of fixes in this GitHub query.

In case you missed it

In case you’ve missed some content on Mobile Blazor Bindings, please check out these recent happenings:

Thank you to community contributors!

I also want to extend a huge thank you to the community members who came over to the GitHub repo and logged issues and sent some wonderful pull requests (several of which are merged and in this release).

This release includes these community code contributions:

  1. Added AutomationId in Element #48 by Kahbazi
  2. Fix src work if NETCore3.0 not installed #55 by 0x414c49
  3. Multi-direction support for Visual Element (RTL, LTR) #59 by 0x414c49

Thank you!

What’s next? Let us know what you want!

We’re listening to your feedback, which has been both plentiful and helpful! We’re also fixing bugs and adding new features. Improved CSS support and inline text are two things we’d love to make available soon.

This project will continue to take shape in large part due to your feedback, so please let us know your thoughts at the GitHub repo or fill out the feedback survey.

Eilon Lipton