Elysia Tools

在一个清晰的工作台里浏览工具、案例、可视化和主题指南。

热门分类

专题

语言
ZHDERUPTENFRES

Elysia Tools

导航

移动开发

Xamarin跨平台开发示例

Xamarin.Forms和Xamarin.Native实现示例,用于使用C#和.NET进行跨平台移动开发

案例

这个案例集合中的条目

代码csharp简单

Xamarin.Forms 基础CRUD操作

使用Xamarin.Forms和SQLite构建跨平台移动应用,实现基础的创建、读取、更新、删除操作

csharp
// XAML - MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamarinCRUDApp.MainPage"
             Title="Contact Manager">

    <StackLayout Padding="20" Spacing="10">
        <Label Text="Contact Manager"
               FontSize="Large"
               FontAttributes="Bold"
               HorizontalOptions="Center" />

        <Entry x:Name="NameEntry" Placeholder="Name" />
        <Entry x:Name="EmailEntry" Placeholder="Email" Keyboard="Email" />
        <Entry x:Name="PhoneEntry" Placeholder="Phone" Keyboard="Telephone" />

        <StackLayout Orientation="Horizontal" HorizontalOptions="Center">
            <Button Text="Add" Clicked="OnAddClicked" />
            <Button Text="Update" Clicked="OnUpdateClicked" />
            <Button Text="Delete" Clicked="OnDeleteClicked" />
        </StackLayout>

        <ListView x:Name="ContactsListView"
                  ItemSelected="OnContactSelected">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Name}"
                              Detail="{Binding Email}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

// C# - Contact.cs
using SQLite;
using System.ComponentModel;

namespace XamarinCRUDApp.Models
{
    public class Contact : INotifyPropertyChanged
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        private string _name;
        public string Name
        {
            get => _name;
            set
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        private string _email;
        public string Email
        {
            get => _email;
            set
            {
                _email = value;
                OnPropertyChanged(nameof(Email));
            }
        }

        private string _phone;
        public string Phone
        {
            get => _phone;
            set
            {
                _phone = value;
                OnPropertyChanged(nameof(Phone));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

// C# - DatabaseService.cs
using SQLite;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using XamarinCRUDApp.Models;

namespace XamarinCRUDApp.Services
{
    public class DatabaseService
    {
        private readonly SQLiteAsyncConnection _database;

        public DatabaseService(string dbPath)
        {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<Contact>().Wait();
        }

        public Task<List<Contact>> GetContactsAsync()
        {
            return _database.Table<Contact>().ToListAsync();
        }

        public Task<Contact> GetContactAsync(int id)
        {
            return _database.Table<Contact>()
                            .Where(c => c.Id == id)
                            .FirstOrDefaultAsync();
        }

        public Task<int> SaveContactAsync(Contact contact)
        {
            if (contact.Id != 0)
            {
                return _database.UpdateAsync(contact);
            }
            else
            {
                return _database.InsertAsync(contact);
            }
        }

        public Task<int> DeleteContactAsync(Contact contact)
        {
            return _database.DeleteAsync(contact);
        }
    }
}
代码csharp中等

Xamarin.Forms 导航与MasterDetail页面

使用MasterDetail页面实现高级导航模式,包含菜单导航、页面转场和移动端专用UX模式

csharp
// XAML - AppShell.xaml
<?xml version="1.0" encoding="UTF-8"?>
<Shell xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:views="clr-namespace:XamarinNavigationApp.Views"
       x:Class="XamarinNavigationApp.AppShell"
       FlyoutHeaderBehavior="FlyoutHeaderBehavior.OnScroll">

    <Shell.FlyoutHeader>
        <Grid BackgroundColor="#2196F3" HeightRequest="150">
            <Grid.RowDefinitions>
                <RowDefinition Height="*" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>

            <Image Grid.Row="0"
                   Source="appicon.png"
                   HeightRequest="60"
                   WidthRequest="60"
                   HorizontalOptions="Center"
                   VerticalOptions="Center" />

            <Label Grid.Row="1"
                   Text="My App"
                   TextColor="White"
                   FontSize="Large"
                   HorizontalTextAlignment="Center" />
        </Grid>
    </Shell.FlyoutHeader>

    <FlyoutItem Title="Home" Icon="home.png">
        <ShellContent Route="home" ContentTemplate="{DataTemplate views:HomePage}" />
    </FlyoutItem>

    <FlyoutItem Title="Products" Icon="products.png">
        <TabBar>
            <ShellContent Title="All Products" Route="products"
                          ContentTemplate="{DataTemplate views:ProductsPage}" />
            <ShellContent Title="Categories" Route="categories"
                          ContentTemplate="{DataTemplate views:CategoriesPage}" />
            <ShellContent Title="Search" Route="search"
                          ContentTemplate="{DataTemplate views:SearchPage}" />
        </TabBar>
    </FlyoutItem>

    <FlyoutItem Title="Profile" Icon="profile.png">
        <ShellContent Route="profile" ContentTemplate="{DataTemplate views:ProfilePage}" />
    </FlyoutItem>

    <FlyoutItem Title="Settings" Icon="settings.png">
        <ShellContent Route="settings" ContentTemplate="{DataTemplate views:SettingsPage}" />
    </FlyoutItem>

    <MenuItem Text="Logout" Icon="logout.png" Clicked="OnLogoutClicked" />
</Shell>

// XAML - HomePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamarinNavigationApp.Views.HomePage"
             Title="Home">

    <RefreshView x:Name="RefreshView" IsRefreshing="{Binding IsRefreshing, Mode=TwoWay}">
        <ScrollView>
            <StackLayout Padding="20" Spacing="20">

                <!-- Welcome Section -->
                <Frame BackgroundColor="#2196F3" Padding="20" CornerRadius="10">
                    <StackLayout>
                        <Label Text="Welcome Back!"
                               TextColor="White"
                               FontSize="24"
                               FontAttributes="Bold" />
                        <Label Text="{Binding UserWelcome}"
                               TextColor="White"
                               FontSize="16"
                               Opacity="0.8" />
                    </StackLayout>
                </Frame>

                <!-- Quick Actions -->
                <Label Text="Quick Actions"
                       FontSize="18"
                       FontAttributes="Bold" />

                <Grid RowSpacing="15" ColumnSpacing="15">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <Frame Grid.Row="0" Grid.Column="0"
                           BackgroundColor="#FF9800" Padding="20"
                           HasShadow="True">
                        <StackLayout>
                            <Image Source="add.png"
                                   WidthRequest="30"
                                   HeightRequest="30"
                                   HorizontalOptions="Center" />
                            <Label Text="Add Item"
                                   TextColor="White"
                                   HorizontalTextAlignment="Center"
                                   FontSize="12" />
                        </StackLayout>
                        <Frame.GestureRecognizers>
                            <TapGestureRecognizer Command="{Binding AddItemCommand}" />
                        </Frame.GestureRecognizers>
                    </Frame>
                </Grid>
            </StackLayout>
        </ScrollView>
    </RefreshView>
</ContentPage>

// C# - HomeViewModel.cs
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace XamarinNavigationApp.ViewModels
{
    public class HomeViewModel : INotifyPropertyChanged
    {
        private bool _isRefreshing;
        private string _userWelcome;

        public bool IsRefreshing
        {
            get => _isRefreshing;
            set
            {
                _isRefreshing = value;
                OnPropertyChanged();
            }
        }

        public string UserWelcome
        {
            get => _userWelcome;
            set
            {
                _userWelcome = value;
                OnPropertyChanged();
            }
        }

        public ObservableCollection<RecentActivity> RecentActivities { get; set; }
        public Command AddItemCommand { get; }
        public Command SearchCommand { get; }
        public Command FavoritesCommand { get; }
        public Command SettingsCommand { get; }
        public Command RefreshCommand { get; }

        public HomeViewModel()
        {
            UserWelcome = "John Doe";
            RecentActivities = new ObservableCollection<RecentActivity>();

            AddItemCommand = new Command(async () => await Shell.Current.GoToAsync("additem"));
            SearchCommand = new Command(async () => await Shell.Current.GoToAsync("search"));
            FavoritesCommand = new Command(async () => await Shell.Current.GoToAsync("favorites"));
            SettingsCommand = new Command(async () => await Shell.Current.GoToAsync("settings"));
            RefreshCommand = new Command(async () => await RefreshData());

            LoadRecentActivities();
        }

        private void LoadRecentActivities()
        {
            RecentActivities.Clear();

            RecentActivities.Add(new RecentActivity
            {
                Title = "New Product Added",
                Description = "Added 'Wireless Headphones' to inventory",
                TimeAgo = "2 hours ago",
                Icon = "add.png"
            });
        }

        private async Task RefreshData()
        {
            IsRefreshing = true;
            await Task.Delay(2000);
            LoadRecentActivities();
            IsRefreshing = false;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class RecentActivity
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string TimeAgo { get; set; }
        public string Icon { get; set; }
    }
}
代码csharp复杂

Xamarin Web API集成与身份验证

构建生产级Xamarin应用,包含REST API集成、JWT身份验证、安全令牌存储和离线同步功能

csharp
// C# - Models/ApiResponse.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace XamarinAPIClient.Models
{
    public class ApiResponse<T>
    {
        public bool Success { get; set; }
        public string Message { get; set; }
        public T Data { get; set; }
        public List<string> Errors { get; set; } = new List<string>();
    }

    public class User
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string PhoneNumber { get; set; }
        public DateTime CreatedAt { get; set; }
        public bool IsActive { get; set; }
    }

    public class LoginRequest
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    public class LoginResponse
    {
        public string Token { get; set; }
        public DateTime ExpiresAt { get; set; }
        public User User { get; set; }
    }

    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public bool IsAvailable { get; set; }
    }
}

// C# - Services/ApiService.cs
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using XamarinAPIClient.Helpers;
using XamarinAPIClient.Models;

namespace XamarinAPIClient.Services
{
    public class ApiService
    {
        private readonly HttpClient _httpClient;
        private readonly IAuthenticationService _authService;

        public ApiService(IAuthenticationService authService)
        {
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri(Settings.ApiBaseUrl)
            };
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            _httpClient.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            _authService = authService;
        }

        private async Task<bool> AddAuthorizationHeaderAsync()
        {
            var token = await _authService.GetTokenAsync();
            if (!string.IsNullOrEmpty(token))
            {
                _httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", token);
                return true;
            }
            return false;
        }

        public async Task<ApiResponse<LoginResponse>> LoginAsync(LoginRequest loginRequest)
        {
            try
            {
                var json = JsonConvert.SerializeObject(loginRequest);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("/api/auth/login", content);

                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<ApiResponse<LoginResponse>>(responseContent);

                if (response.IsSuccessStatusCode && result.Success)
                {
                    await _authService.SaveTokenAsync(result.Data.Token, result.Data.ExpiresAt);
                    await _authService.SaveUserAsync(result.Data.User);
                }

                return result;
            }
            catch (Exception ex)
            {
                return new ApiResponse<LoginResponse>
                {
                    Success = false,
                    Message = $"Network error: {ex.Message}"
                };
            }
        }

        public async Task<ApiResponse<List<Product>>> GetProductsAsync()
        {
            try
            {
                if (!await AddAuthorizationHeaderAsync())
                {
                    return new ApiResponse<List<Product>>
                    {
                        Success = false,
                        Message = "Authorization required"
                    };
                }

                var response = await _httpClient.GetAsync("/api/products");

                if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    await _authService.SignOutAsync();
                    return new ApiResponse<List<Product>>
                    {
                        Success = false,
                        Message = "Session expired. Please login again."
                    };
                }

                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<ApiResponse<List<Product>>>(responseContent);

                return result;
            }
            catch (Exception ex)
            {
                return new ApiResponse<List<Product>>
                {
                    Success = false,
                    Message = $"Network error: {ex.Message}"
                };
            }
        }

        public async Task<ApiResponse<LoginResponse>> RefreshTokenAsync()
        {
            try
            {
                var response = await _httpClient.PostAsync("/api/auth/refresh", null);
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<ApiResponse<LoginResponse>>(responseContent);

                if (response.IsSuccessStatusCode && result.Success)
                {
                    await _authService.SaveTokenAsync(result.Data.Token, result.Data.ExpiresAt);
                    await _authService.SaveUserAsync(result.Data.User);
                }

                return result;
            }
            catch (Exception ex)
            {
                return new ApiResponse<LoginResponse>
                {
                    Success = false,
                    Message = $"Token refresh error: {ex.Message}"
                };
            }
        }
    }
}

// C# - Services/AuthenticationService.cs
using Newtonsoft.Json;
using System;
using XamarinAPIClient.Helpers;
using XamarinAPIClient.Models;
using System.Threading.Tasks;
using Plugin.SecureStorage;

namespace XamarinAPIClient.Services
{
    public interface IAuthenticationService
    {
        Task<bool> IsAuthenticatedAsync();
        Task<bool> LoginAsync(string email, string password);
        Task SignOutAsync();
        Task<User> GetCurrentUserAsync();
        Task<string> GetTokenAsync();
        Task SaveTokenAsync(string token, DateTime expiresAt);
        Task SaveUserAsync(User user);
    }

    public class AuthenticationService : IAuthenticationService
    {
        private readonly ApiService _apiService;

        public AuthenticationService(ApiService apiService)
        {
            _apiService = apiService;
        }

        public async Task<bool> IsAuthenticatedAsync()
        {
            try
            {
                var token = await GetTokenAsync();
                var expiresAt = CrossSecureStorage.Current.GetValue("token_expires");

                if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(expiresAt))
                    return false;

                var expiryDate = DateTime.Parse(expiresAt);

                // Refresh token if it's expired or about to expire (within 5 minutes)
                if (expiryDate < DateTime.UtcNow.AddMinutes(5))
                {
                    var refreshResult = await _apiService.RefreshTokenAsync();
                    return refreshResult.Success;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> LoginAsync(string email, string password)
        {
            try
            {
                var loginRequest = new LoginRequest
                {
                    Email = email,
                    Password = password
                };

                var response = await _apiService.LoginAsync(loginRequest);
                return response.Success;
            }
            catch
            {
                return false;
            }
        }

        public async Task SignOutAsync()
        {
            CrossSecureStorage.Current.DeleteKey("auth_token");
            CrossSecureStorage.Current.DeleteKey("refresh_token");
            CrossSecureStorage.Current.DeleteKey("token_expires");
            CrossSecureStorage.Current.DeleteKey("user_data");
        }

        public async Task<User> GetCurrentUserAsync()
        {
            try
            {
                var userData = CrossSecureStorage.Current.GetValue("user_data");
                if (!string.IsNullOrEmpty(userData))
                {
                    return JsonConvert.DeserializeObject<User>(userData);
                }
            }
            catch { }

            return null;
        }

        public async Task<string> GetTokenAsync()
        {
            return await Task.FromResult(
                CrossSecureStorage.Current.GetValue("auth_token"));
        }

        public async Task SaveTokenAsync(string token, DateTime expiresAt)
        {
            await Task.Run(() =>
            {
                CrossSecureStorage.Current.SetValue("auth_token", token);
                CrossSecureStorage.Current.SetValue("token_expires", expiresAt.ToString());
            });
        }

        public async Task SaveUserAsync(User user)
        {
            await Task.Run(() =>
            {
                var userData = JsonConvert.SerializeObject(user);
                CrossSecureStorage.Current.SetValue("user_data", userData);
            });
        }
    }
}

工具

经常与该案例搭配使用的工具

相关内容

相关案例集合

相关内容

相关专题

专题

一张照片生成全平台社交媒体图片套件

以一张母版照片为源头,导出 Instagram、TikTok、LinkedIn、X 等平台的正确尺寸裁剪,预览字幕安全区,组装九宫格切图与多图拼贴,并在账号语气允许时附加命名清晰的风格化变体。

专题

界面截图结构化、人工校对与开发交付

把一张获授权的界面截图整理为经人工校对的组件树、结构 JSON 与开发说明,记录坐标来源、识别遗漏和修改依据,不把视觉推断当成原始代码。

专题

药代动力学教学模型与结果核查

用于教学或 QA 的药代公式、模型假设和结果一致性核查,不提供用药剂量、诊断或临床建议。

专题

播客录制、剪辑与交付

修复远程嘉宾声音,清理口播瑕疵,完成剪辑、母带、广告标记、响度检查和平台交付预检。

首页
工具3212
案例593
可视化471
文件查看器103
专题239
标签333
图像、音频与视频657

图像、音频、视频处理、转换与优化工具

数学、日期与金融647

计算器、数值计算、日期逻辑、统计与金融工具

设计与颜色298

颜色、版式、图形、视觉样式与设计辅助工具

文本与写作209

写作、清洗、格式化、提取与文本分析工具

开发与 Web193

开发者工具、网络处理、Web 调试与自动化辅助工具

转换与编码175

格式、文件、压缩包、单位与编码转换工具

潜客测验发布与联系人交接
讣告、悼词与纪念卡的家属复核及交付
本地习惯记录的备份、恢复演练与分享前检查
长文改编 X 串文与 LinkedIn 帖子的事实复核与交付
Markdown 互动课件审校、离线演示与交付

© 2026 Elysia Tools. 保留所有权利。

文档价格关于我们服务条款隐私政策Cookie 政策联系我们

Media

AVI转MP4转换器

将AVI视频文件转换为MP4格式

Media

MP4转AVI转换器

将MP4视频文件转换为AVI格式

Media

批量视频转换器

批量转换多个视频文件格式,支持 MP4、WebM、MKV、AVI、MOV、FLV,支持质量设置和批量处理

Media

视频剪辑器

精确剪辑视频片段,支持多种格式和质量设置

Media

视频转APNG

将视频片段转换为APNG(动画PNG)格式,支持透明度且质量优于GIF

Media

视频转GIF优化版

将视频转换为优化后的GIF格式,支持高级压缩设置

Media

视频转图片序列

将视频帧提取为图片序列,支持自定义帧率、质量和输出格式

Media

视频修剪

快速修剪视频片段 - 使用快速无损处理从视频中提取片段

移动开发

Flutter 示例

Flutter Dart 移动开发框架示例,包括小部件、状态管理、导航和平台集成

移动开发

React Native 示例

React Native 跨平台移动开发示例,包括组件、导航、状态管理和原生集成

移动开发

Ionic 示例

Ionic 混合移动应用框架示例,包括组件、导航、状态管理和原生集成

测试

BDD with Cucumber - 行为驱动开发实践

全面的 Cucumber BDD 示例,包括功能文件、步骤定义、数据表格、钩子和高级 BDD 模式,用于协作开发

消息

Apache Pulsar 示例

Apache Pulsar 示例,包括发布订阅、读取器、不同订阅类型的消费者、模式管理和分层存储,适用于企业级消息传递

媒体

SVG示例

可缩放矢量图形(SVG)示例,展示各种SVG功能和技术