创建使用C#和XML的Xamarin.Forms深链接应用程序

发布:2024-09-02 14:42 阅读:39 点赞:0

在本文中,我们将探讨如何使用 C# 和 XML 在 Xamarin.Forms 中创建深度链接应用。以电子邮件客户端为例,当用户点击收到的电子邮件通知时,它将打开一个深度链接,直接跳转到应用中的特定邮件。深度链接还允许 Google 索引您的应用,并在搜索结果中链接到应用的特定部分。深度链接在 Google 搜索结果中显示,并可以带用户直接跳转到应用的特定部分。

步骤 1:创建 Xamarin.Forms 应用

  1. 打开 Visual Studio,通过 文件 >> 新建 >> Visual C# >> 跨平台 >> 跨平台应用 (Xamarin.Native 或 Xamarin.Forms) 创建一个新的项目。
  2. 选择 Blank App >> Xamarin.Forms >> .Portable Class Library 并点击 OK。
  3. 项目名称设置为 DeepLinking。

步骤 2:添加 NuGet 包

  1. 在解决方案资源管理器中,右键点击解决方案,选择 管理 NuGet 包。
  2. 选择以下 NuGet 包并安装到您的项目中:
    • SQLite-net-pcl
    • SQLitePCL.bundle_green
    • SQLitePCL.raw
    • SQLitePCL.Raw.bundle_green
    • SQLitePCLRaw.core

步骤 3:创建数据库类

  1. 在解决方案资源管理器中,右键点击项目名称(Portable),选择 添加 >> 新建文件夹,命名为 Data。
  2. 在 Data 文件夹中,右键点击并添加一个类,命名为 TodoItemDatabase。
  3. 用以下代码替换 TodoItemDatabase.cs 的内容:
using System.Collections.Generic;
using System.Linq;
using SQLite;
using Xamarin.Forms;
namespace DeepLinking
{
    public class TodoItemDatabase
    {
        static readonly object locker = new object();
        readonly SQLiteConnection database;

        public TodoItemDatabase()
        {
            database = DependencyService.Get().GetConnection();  // 获取应用的数据库连接
            database.CreateTable();                              // 为数据库创建表
        }
        public IEnumerable GetItems()
        {
            lock (locker)
            {
                return database.Table().ToList();
            }
        }
        public TodoItem Find(string id)
        {
            lock (locker)
            {
                return database.Table().FirstOrDefault(i => i.ID == id);
            }
        }
        public int Insert(TodoItem item)
        {
            lock (locker)
            {
                return database.Insert(item);
            }
        }
        public int Update(TodoItem item)
        {
            lock (locker)
            {
                return database.Update(item);
            }
        }
        public int Delete(string id)
        {
            lock (locker)
            {
                return database.Delete(id);
            }
        }
    }
}

步骤 4:创建模型类

  1. 在解决方案资源管理器中,创建一个新的文件夹 Models。
  2. 在 Models 文件夹中,添加一个类,命名为 TodoItem。
  3. 用以下代码替换 TodoItem.cs 的内容:
using SQLite;
namespace DeepLinking
{
    public class TodoItem
    {
        [PrimaryKey]
        public string ID { getset; }  // 主键
        public string Name { getset; }  // 任务名称
        public string Notes { getset; }  // 备注
        public bool Done { getset; }  // 完成状态
    }
}

步骤 5:创建视图和视图模型

  1. 在解决方案资源管理器中,创建一个新的文件夹 Views。
  2. 在 Views 文件夹中,添加两个类和两个设计页面,分别命名为 TodoItemPage.xaml, TodoItemPageCS.cs, TodoListPage.xaml, TodoListPageCS.cs。
  3. 用以下代码替换 TodoItemPage.xaml 的内容:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  x:Class="DeepLinking.TodoItemPage" Title="Todo Item">
    <StackLayout VerticalOptions="StartAndExpand">
        <Label Text="Name" />
        <Entry Text="{Binding Path=Name}" Placeholder="task name" />
        <Label Text="Notes" />
        <Entry Text="{Binding Path=Notes}" />
        <Label Text="Done" />
        <Switch IsToggled="{Binding Path=Done}" />
        <Button Text="Save" Clicked="OnSaveActivated" />
        <Button Text="Delete" Clicked="OnDeleteActivated" />
        <Button Text="Cancel" Clicked="OnCancelActivated" />
    StackLayout>
ContentPage>
  1. 用以下代码替换 TodoItemPage.xaml.cs 的内容:
using System;
using System.Net;
using Xamarin.Forms;
namespace DeepLinking
{
    public partial class TodoItemPage : ContentPage
    {
        IAppLinkEntry appLink;
        bool isNewItem;
        public TodoItemPage() : this(false)
        {
        }
        public TodoItemPage(bool isNew = false)
        {
            InitializeComponent();
            isNewItem = isNew;
        }
        protected override void OnAppearing()
        {
            appLink = GetAppLink(BindingContext as TodoItem);
            if (appLink != null)
            {
                appLink.IsLinkActive = true;
            }
        }
        protected override void OnDisappearing()
        {
            if (appLink != null)
            {
                appLink.IsLinkActive = false;
            }
        }
        async void OnSaveActivated(object sender, EventArgs e)
        {
            var todoItem = (TodoItem)BindingContext;

            if (isNewItem)
            {
                App.Database.Insert(todoItem);
            }
            else
            {
                App.Database.Update(todoItem);
            }
            appLink = GetAppLink(BindingContext as TodoItem);
            Application.Current.AppLinks.RegisterLink(appLink);

            await Navigation.PopAsync();
        }
        async void OnDeleteActivated(object sender, EventArgs e)
        {
            var todoItem = (TodoItem)BindingContext;
            App.Database.Delete(todoItem.ID);
            Application.Current.AppLinks.DeregisterLink(appLink);

            await Navigation.PopAsync();
        }
        async void OnCancelActivated(object sender, EventArgs e)
        {
            await Navigation.PopAsync();
        }
        AppLinkEntry GetAppLink(TodoItem item)
        {
            var pageType = GetType().ToString();
            var pageLink = new AppLinkEntry
            {
                Title = item.Name,
                Description = item.Notes,
                AppLinkUri = new Uri(string.Format("http://{0}/{1}?id={2}", App.AppName, pageType, WebUtility.UrlEncode(item.ID)), UriKind.RelativeOrAbsolute),
                IsLinkActive = true,
                Thumbnail = ImageSource.FromFile("monkey.png")
            };
            pageLink.KeyValues.Add("contentType""TodoItemPage");
            pageLink.KeyValues.Add("appName", App.AppName);
            pageLink.KeyValues.Add("companyName""Xamarin");
            return pageLink;
        }
    }
}
  1. 用以下代码替换 TodoListPage.xaml 的内容:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  x:Class="DeepLinking.TodoListPage" Title="Todo">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="+" Clicked="OnAddItemClicked">
            <ToolbarItem.Icon>
                <OnPlatform x:TypeArguments="FileImageSource">
                    <On Platform="Android" Value="plus.png" />
                OnPlatform>
            ToolbarItem.Icon>
        ToolbarItem>
    ContentPage.ToolbarItems>
    <ListView x:Name="listView" ItemSelected="OnItemSelected">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Padding="20,0,0,0" HorizontalOptions="StartAndExpand" Orientation="Horizontal">
                        <Label Text="{Binding Name}" VerticalTextAlignment="Center" />
                        <Image Source="check.png" IsVisible="{Binding Done}" />
                    StackLayout>
                ViewCell>
            DataTemplate>
        ListView.ItemTemplate>
    ListView>
ContentPage>
  1. 用以下代码替换 TodoListPage.xaml.cs 的内容:
using System;
using Xamarin.Forms;
namespace DeepLinking
{
    public partial class TodoListPage : ContentPage
    {
        public TodoListPage()
        {
            InitializeComponent();
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();
            listView.ItemsSource = App.Database.GetItems();
        }
        protected override void OnDisappearing()
        {
            base.OnDisappearing();
            listView.ItemsSource = null;
        }
        async void OnAddItemClicked(object sender, EventArgs e)
        {
            var todoItem
 = new TodoItem()
            {
                ID = Guid.NewGuid().ToString()
            };
            var todoPage = new TodoItemPage(true);
            todoPage.BindingContext = todoItem;
            await Navigation.PushAsync(todoPage);
        }
        async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var todoItem = e.SelectedItem as TodoItem;
            var todoPage = new TodoItemPage
            {
                BindingContext = todoItem
            };
            await Navigation.PushAsync(todoPage);
        }
    }
}

步骤 6:创建 SQLite 接口

  1. 在解决方案资源管理器中,右键点击解决方案,选择 添加 >> 类。
  2. 命名为 ISQLite。
  3. 用以下代码替换 ISQLite.cs 的内容:
using SQLiteConnection;
namespace DeepLinking
{
    public interface ISQLite
    {
        SQLiteConnection GetConnection();
    }
}

步骤 7:配置 App 类

  1. 在解决方案资源管理器中,打开 App.cs 文件。
  2. 用以下代码替换 App.cs 的内容:
public App()
{
    Database = new TodoItemDatabase();
    MainPage = new NavigationPage(new TodoListPage());
}

步骤 8:构建和运行应用

  1. 完成设计视图后,点击 构建 菜单,选择 配置管理器。
  2. 在弹出窗口中,配置您的启动项目。
  3. 点击 F5 或运行您的项目。

通过以上步骤,我们成功创建了一个深度链接应用。后续我们将继续探讨更多的 Xamarin.Forms 应用开发技巧。