Walkthrough: Use Xamarin. Forms to develop applications of the nature (VB ),
Overview
Xamarin, a cross-platform development framework using mono and. net core, has been developing over the past few years. After being acquired by Microsoft, Xamarin provides a free version of Xamarin for Visual Studio for individual developers, attracting the attention of more developers.
Xamarin. Forms is easier to use, because it can be run everywhere once written in this way. But I don't know why, Xamarin currently only supports C #. They claim that the supported F # is actually only more documentation and less commonly used tools than C #, and lacks the support of important functions such as the post-Xaml code generator.
VB is even more left out. The user suggested that Xamarin support the number of votes for VB. As of this blog post, there will already be 397 votes (view votes), but Xamarin does not explicitly indicate whether it is supported by VB.
Fortunately, Xamarin does not block the development staff who are used to using VB. There are several VB code files hidden in the Xamarin GitHub sample library. There is a tutorial on using VB code in Xamarin in an inconspicuous corner of the tutorial area. Both the tutorial and sample files use C # To create Xamarin. forms project, and then replace the C # portable class library with the VB portable class library, you can use VB to write the shared UI code and business logic code. The defect is that you cannot use a Xaml file to generate the required code.
Now, I will fill in the actual VB development tutorial for Xamarin.
Step 1: Create a project
Follow the Xamarin. Forms tutorial to create a C # Xamarin. Forms portable project. Delete the C # portable class library and replace it with a new VB portable project with the same project name and namespace as the target. Add a reference to the portable class library again in the C # project. If necessary, add Xamarin. Forms to the default import in the VB project.
Step 2: update the Nuget package
Use the Nuget Package Manager to update the Xamarin. Forms package for each project. If you ignore this step, it will cause a running error.
Step 3: Create an App. vb File
The default template creates the Class1.vb file. Rename it as App. vb and fill in the following content:
Public Class App Inherits Application Sub New() MainPage = New NavigationPage(New MainPage) End SubEnd Class
You can use NavigationPage to facilitate navigation between pages.
After this code is inserted, intelliisense will prompt you to create the MainPage class. Click create in the new file.
Step 4: Create a page in the software
Assume that the first page is ContentPage. Modify the automatically generated inherited statement.
Public Class MainPage Inherits ContentPageEnd Class
Since Xamarin does not allow the use of Xaml in VB, we should not use a development method similar to UWP. Let's return to the original ecology and look for the feeling of using Winform to code ten years ago.
Create a file named MainPage. Designer. vb.
As in the past, the MainPage class in this file is marked with Partial
Option Strict OnPartial Public Class MainPageEnd Class
Readers can guess what to do next. Write constructor and InitializeComponents method.
Protected Sub InitializeComponents() End Sub Sub New() InitializeComponents() End Sub
Assume that a control similar to the Windows Store is to be placed on the top of the page. Below is a set of banners for introduction.
First, if there are many things below, the page may not be able to fit. Therefore, a Scroll display box is required. The contents are arranged in descending order. The top control is a carousel.
WithEvents sclContentViewer As New ScrollView, stkContent As New StackLayout, crsBanner As New CarouselControl
Because Xamarin does not have a carousel, the next step is to create a user control.
Step 5: create a user control
Use intelliisense to quickly create a CarouselControl. vb File
Similarly, manually create the CarouselControl. Designer. vb file.
The carousel control has a left turn and right turn button. The content to be displayed is pressed under the button. You can turn left or right by using a sliding gesture. Clicking this button will trigger the click event. There is an indicator at the bottom of the control to display the rotation progress of the carousel.
Partial Public Class CarouselControl Inherits ContentView WithEvents btnLeft As New Button With { .Text = "<", .HorizontalOptions = LayoutOptions.Start, .VerticalOptions = LayoutOptions.Fill, .FontSize = 32, .BackgroundColor = Color.FromRgba(0, 0, 0, 0.01), .BorderWidth = 0, .TextColor = Color.FromRgba(0, 0, 0, 0.7), .BorderColor = Color.Transparent }, btnRight As New Button With { .Text = ">", .HorizontalOptions = LayoutOptions.End, .VerticalOptions = LayoutOptions.Fill, .FontSize = 32, .BackgroundColor = Color.FromRgba(0, 0, 0, 0.01), .BorderWidth = 0, .TextColor = Color.FromRgba(0, 0, 0, 0.7), .BorderColor = Color.Transparent }, cntDetail As New Grid, grdItemView As New Grid, panDetector As New PanGestureRecognizer, layoutRoot As New StackLayout, indicator As New CarouselIndicator With { .HorizontalOptions = LayoutOptions.Center } Sub New() InitializeComponents() End Sub Protected Sub InitializeComponents() With grdItemView.Children .Add(cntDetail) .Add(btnLeft) .Add(btnRight) End With GestureRecognizers.Add(panDetector) layoutRoot.Children.Add(grdItemView) layoutRoot.Children.Add(indicator) Content = layoutRoot End SubEnd Class
Due to the limited space, the rotator code of the Trojan can be found at the GitHub link at the end of the article.
Return to the file where the carousel class has no division.
There are many things to write about this control. I will give an important explanation. Processing events is the same as using Winform. You can generate blank event processing code by clicking controls and events in the drop-down list.
The following uses sliding Gesture Recognition as an example to populate the automatically generated code with the code that handles scrolling.
Private Sub panDetector_PanUpdated(sender As Object, e As PanUpdatedEventArgs) Handles panDetector.PanUpdated If Math.Abs(e.TotalX) > Math.Abs(e.TotalY) Then Dim threshold = btnLeft.Width If e.TotalX > threshold Then MoveBack() ElseIf e.TotalX < -threshold Then MoveForward() End If End If End Sub
The banner MediumBanner method is similar. If you do not want to write a new template for the ContentView control, it is appropriate to create a new banner control.
The data binding of the banner control is relatively simple and some code is pasted.
The first step is to set binding in the constructor. The concept here is similar to that of UWP data binding. Note that some converters need to be written by themselves.
imgIcon.SetBinding(Image.SourceProperty, NameOf(MediumBannerData.IconImage), converter:=New EmbeddedImageLoader)
After binding is set, specify the data context when creating the control. Note that the data context attribute of Xamarin is BindingContext rather than DataContext.
WithEvents btnAbout As New MediumBanner With {. BindingContext = New MediumBannerData ("aboutbanner.png", "about this software", "about.png ")}
If a widget does not have a click event, you can bind data to the Command attribute of the click gesture reader, or use its Tapped event to write a Clicked event.
btnTapHitTest.SetBinding(TapGestureRecognizer.CommandProperty, NameOf(CarouselControlDefaultModel.OnClick))
Step 6: Use the Mvvm Mode
Using the Mvvm mode can save a lot of trouble.
First, create a Model.
Public Class CarouselControlDefaultModel Sub New(functionName As String, embeddedImageFileName As String, onClick As ICommand) Me.FunctionName = functionName Me.EmbeddedImageFileName = embeddedImageFileName Me.OnClick = onClick End Sub Public Property FunctionName As String Public Property EmbeddedImageFileName As String Public Property OnClick As ICommandEnd Class
Next, the corresponding ViewModel
The type of the Set depends on the degree to which the corresponding control is implemented.
Public Class HoneyCarouselViewModel Sub New(items As List(Of CarouselControlDefaultModel)) Me.Items = items End Sub Public Property Items As New List(Of CarouselControlDefaultModel)End Class
Data should be stored in the resource file. If there is less data, you can directly write it into the code.
The binding Code of View and ViewModel is written on the corresponding page.
Sub New() InitializeComponents() crsBanner.ItemsSource = vm.Items End Sub
Repeat the previous steps until the homepage is finished.
Step 7: process the navigation between pages
The navigation code is simple.
Whether you navigate to a page or back, you can use the Navigation object to perform operations.
Private Sub btnAbout_Clicked(sender As Object, e As EventArgs) Handles btnAbout.Clicked Navigation.PushAsync(New AboutPage) End Sub
Step 8: process specific platform Functions
I searched the Xamarin. Forms tutorial and did not find that the browser function was enabled. If this function is missing, you have to implement it in other projects.
Create a class or a module, including the process of opening events for the browser and triggering events.
Public Class HyperlinkNavigationService Public Shared Event NavigationRequested(link As Uri) Public Shared Sub NavigateTo(link As Uri) RaiseEvent NavigationRequested(link) End SubEnd Class
Process browser Navigation Request events in Android Projects
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); HyperlinkNavigationService.NavigationRequested += HyperlinkNavigationService_NavigationRequested; global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } private void HyperlinkNavigationService_NavigationRequested(Uri link) { StartActivity(new Intent("android.intent.action.VIEW", Android.Net.Uri.Parse(link.OriginalString))); } protected override void OnDestroy() { base.OnDestroy(); HyperlinkNavigationService.NavigationRequested -= HyperlinkNavigationService_NavigationRequested; } }
Similarly, navigation events are handled in UWP, Win 8.1, WP 8.1, and IOS projects.
Other problems can also be solved in this way, and functions on specific platforms can be called through events.
Step 9: Process Resource and application Definitions
Before release, you must replace your own resources with your own re-designed resources. Generally, image resources and application definitions must be modified.
It is best to classify resources embedded in a portable project in folders without duplicate names.
Detailed examples
Address of the sample project: https://github.com/NWU1902/ZhongTianSale
The sample project only contains the portable class library and does not have any project on a specific platform.