基础学习
Xamarin 基础
Syncfusion 插件
获取 License
License & Downloads -> get License -> 输入信息 -> 等待
文件目录
ProjectName
API // RestFul API 文件夹
Fonts // 引入字体
Models // 对象模型
PopUpPage // PopUp 界面
View // 视图
ViewModels // MVVM 文件夹
App.xaml.cs
App.xaml.cs // 配置 插件
MainPage.xaml // 默认主页(可以删除)
ProjectName.Android
Resources
drawable // 引入图片文件夹
MainActivity.cs // Android 配置
ProjectName.iOS
安装包
// 基本安装包
CardsView
Newtonsoft.Json
Rg.Plugins.Popup
Xam.Plugins.Forms.ImageCircle
Xamarin.Essentials
Xamarin.FFImageLoading.Forms
Xamarin.FOrms.PancakeView
// 获取通知
OneSignalSDK.Xamarin
// Syncfusion 安装包请查看 Documentation,安装你想要的
Syncfusion.Xamarin.Buttons
Syncfusion.Xamarin.Core
Syncfusion.Xamarin.SfAutoComplete
Syncfusion.Xamarin.SfMaskedEdit
Syncfusion.Xamarin.SfRotator
Syncfusion.Xamarin.SfTabView
App.xaml.cs 配置
using System;
using Cinema.View;
using OneSignalSDK.Xamarin;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
// 引入 字体
[assembly: ExportFont("ZCOOLKuaiLe-Regular.ttf", Alias = "AC")]
[assembly: ExportFont("Kalam-Regular.ttf", Alias = "BC")]
[assembly: ExportFont("Playball-Regular.ttf", Alias = "CC")]
[assembly: ExportFont("Merienda-Bold.ttf", Alias = "DC")]
[assembly: ExportFont("BerkshireSwash-Regular.ttf", Alias = "EC")]
[assembly: ExportFont("ConcertOne-Regular.ttf", Alias = "FC")]
[assembly: ExportFont("Viga-Regular.ttf", Alias = "GC")]
[assembly: ExportFont("LibreBaskerville-Italic.ttf", Alias = "HC")]
// 引入 字体
[assembly: ExportFont("Exo2-VariableFont_wght.ttf", Alias = "AA")]
[assembly: ExportFont("BebasNeue-Regular.ttf", Alias = "BA")]
[assembly: ExportFont("NotoSerifSC-Bold.ttf", Alias = "CA")]
[assembly: ExportFont("Signika-VariableFont_wght.ttf", Alias = "DA")]
[assembly: ExportFont("AbrilFatface-Regular.ttf", Alias = "EA")]
[assembly: ExportFont("Kalam-Bold.ttf", Alias = "FA")]
namespace Cinema
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
// 注册 Syncfusion
Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("放入你自己的License,这样就不会出现烦人的通知广告");
// 默认 启动 首页
MainPage = new NavigationPage(new Start());
// 配置 通知 信息
OneSignal.Default.Initialize("放入你自己的,去官网注册");
OneSignal.Default.PromptForPushNotificationsWithUserResponse();
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
Android
MainActivity.cs 配置
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using ImageCircle.Forms.Plugin.Droid;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
using OneSignalSDK.Xamarin;
namespace Cinema.Droid
{
[Activity(Label = "App 名称", Icon = "@drawable/App Icon 名称", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// 手机 信息 通知
OneSignal.Default.Initialize("放入你自己的,去官网注册");
OneSignal.Default.PromptForPushNotificationsWithUserResponse();
// PopUp 配置
Rg.Plugins.Popup.Popup.Init(this);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
// 圆形图片 配置
ImageCircleRenderer.Init();
// App Status Bar 颜色 配置
Window.SetStatusBarColor(Android.Graphics.Color.Rgb(45, 45, 46));
FFImageLoading.Forms.Platform.CachedImageRenderer.Init(true);
LoadApplication(new App());
Xamarin.Forms.Application.Current.On<Xamarin.Forms.PlatformConfiguration.Android>().UseWindowSoftInputModeAdjust(WindowSoftInputModeAdjust.Resize);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
字体 引入
右键 -> 属性 -> 选择生成操作 -> 嵌入的资源
然后在 App.xaml.cs 配置
[assembly: ExportFont("ZCOOLKuaiLe-Regular.ttf", Alias = "AC")]
[assembly: ExportFont("Kalam-Regular.ttf", Alias = "BC")]
[assembly: ExportFont("Playball-Regular.ttf", Alias = "CC")]
开始
API
UserApi 例子
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Cinema.Models;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Newtonsoft.Json;
using Cinema.ViewModel;
using System.Linq;
namespace Cinema.API
{
public class UserDB
{
// 默认 API URL
const string baseUrl = "http://10.0.2.2:5041/api/";
HttpClient client = new HttpClient();
public static string JWBToken = null;
public static int userID = 0;
// Admin Token
public void Token_Admin()
{
Admin ad = new Admin()
{
Username = "hoo",
Password = "hoo"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
StringContent content = new StringContent(JsonConvert.SerializeObject(ad), Encoding.UTF8, "application/json");
var respose = client.PostAsync("AdminToken", content).Result;
if (respose.IsSuccessStatusCode)
{
string token = respose.Content.ReadAsStringAsync().Result;
if (token != "Invalid credentials")
{
JWBToken = token;
}
}
}
}
// 用户 Token
public void Token_User()
{
string Username = Preferences.Get("Username", string.Empty);
string Password = Preferences.Get("Password", string.Empty);
User user = new User()
{
Username = Username,
Password = Password
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
var respose = client.PostAsync("UserToken", content).Result;
if (respose.IsSuccessStatusCode)
{
string token = respose.Content.ReadAsStringAsync().Result;
if (token != "Invalid credentials")
JWBToken = token;
}
}
}
// 获取 所有 用户 Token——Admin
public async Task<ObservableCollection<User>> GetAllUser_Api()
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWBToken);
client.BaseAddress = new Uri(baseUrl);
var respose = client.GetAsync("User").Result;
if (respose.IsSuccessStatusCode)
{
string jsonString = respose.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<ObservableCollection<User>>(jsonString);
}
return null;
}
// 获取 所有 用户 Token——Admin 主
public ObservableCollection<User> GetAllUser()
{
Token_Admin();
return GetAllUser_Api().Result;
}
// 获取 所有 用户 Token——User
public User GetAllUser_One()
{
string Username = Preferences.Get("Username", string.Empty);
string Password = Preferences.Get("Password", string.Empty);
var userData = GetAllUser();
var data = userData.Where(x => x.Username == Username & x.Password == Password).FirstOrDefault();
if (data != null)
{
return data;
}
return null;
}
// 获取 所有 用户 Token——User 主
public ObservableCollection<User> GetAllUser_User()
{
Token_User();
return GetAllUser_Api().Result;
}
// 创建
public async Task CreateUser_Api(User user)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWBToken);
client.BaseAddress = new Uri(baseUrl);
var respose = client.GetAsync("User").Result;
if (respose.IsSuccessStatusCode)
{
var jsonStr = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
await client.PostAsync(baseUrl + "User", jsonStr);
}
}
// 创建 主
public async Task CreateUser(User user)
{
Token_Admin();
await CreateUser_Api(user);
}
// 修改
public async Task EditUser_Api(User user)
{
var client2 = new HttpClient();
// 设置 HttpClient 实例的属性
client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWBToken);
client2.BaseAddress = new Uri(baseUrl);
var response = await client2.GetAsync("User");
if (response.IsSuccessStatusCode)
{
var jsonStr = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
await client.PutAsync(baseUrl + "User/" + user.UserID, jsonStr);
}
}
// 修改 主
public async Task EditUser(User user)
{
Token_User();
EditUser_Api(user);
}
}
}
其他 例子
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using Cinema.Models;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Xamarin.Essentials;
using System.Linq;
namespace Cinema.API
{
public class ActorDB
{
const string baseUrl = "http://10.0.2.2:5041/api/";
HttpClient client = new HttpClient();
public static string JWBToken = null;
public static int userID = 0;
public void Token_Admin()
{
Admin ad = new Admin()
{
Username = "hoo",
Password = "hoo"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
StringContent content = new StringContent(JsonConvert.SerializeObject(ad), Encoding.UTF8, "application/json");
var respose = client.PostAsync("AdminToken", content).Result;
if (respose.IsSuccessStatusCode)
{
string token = respose.Content.ReadAsStringAsync().Result;
if (token != "Invalid credentials")
{
JWBToken = token;
}
}
}
}
public void Token_User()
{
string Username = Preferences.Get("Username", string.Empty);
string Password = Preferences.Get("Password", string.Empty);
User user = new User()
{
Username = Username,
Password = Password
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
var respose = client.PostAsync("UserToken", content).Result;
if (respose.IsSuccessStatusCode)
{
string token = respose.Content.ReadAsStringAsync().Result;
if (token != "Invalid credentials")
JWBToken = token;
}
}
}
public async Task<ObservableCollection<Actor>> GetAllActor_Api()
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWBToken);
client.BaseAddress = new Uri(baseUrl);
var respose = client.GetAsync("Actor").Result;
if (respose.IsSuccessStatusCode)
{
string jsonString = respose.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<ObservableCollection<Actor>>(jsonString);
}
return null;
}
public ObservableCollection<Actor> GetAllActor()
{
Token_Admin();
return GetAllActor_Api().Result;
}
public ObservableCollection<Actor> GetAllActor_User()
{
Token_User();
return GetAllActor_Api().Result;
}
}
}
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using Cinema.Models;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Xamarin.Essentials;
namespace Cinema.API
{
public class HallDB
{
const string baseUrl = "http://10.0.2.2:5041/api/";
HttpClient client = new HttpClient();
public static string JWBToken = null;
public static int userID = 0;
public void Token_Admin()
{
Admin ad = new Admin()
{
Username = "hoo",
Password = "hoo"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
StringContent content = new StringContent(JsonConvert.SerializeObject(ad), Encoding.UTF8, "application/json");
var respose = client.PostAsync("AdminToken", content).Result;
if (respose.IsSuccessStatusCode)
{
string token = respose.Content.ReadAsStringAsync().Result;
if (token != "Invalid credentials")
{
JWBToken = token;
}
}
}
}
public void Token_User()
{
string Username = Preferences.Get("Username", string.Empty);
string Password = Preferences.Get("Password", string.Empty);
User user = new User()
{
Username = Username,
Password = Password
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseUrl);
StringContent content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json");
var respose = client.PostAsync("UserToken", content).Result;
if (respose.IsSuccessStatusCode)
{
string token = respose.Content.ReadAsStringAsync().Result;
if (token != "Invalid credentials")
JWBToken = token;
}
}
}
public async Task<ObservableCollection<Hall>> GetAllHall_Api()
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWBToken);
client.BaseAddress = new Uri(baseUrl);
var respose = client.GetAsync("Hall").Result;
if (respose.IsSuccessStatusCode)
{
string jsonString = respose.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<ObservableCollection<Hall>>(jsonString);
}
return null;
}
public ObservableCollection<Hall> GetAllHall()
{
Token_Admin();
return GetAllHall_Api().Result;
}
public ObservableCollection<Hall> GetAllHall_User()
{
Token_User();
return GetAllHall_Api().Result;
}
}
}
Session(Preferences)
using Xamarin.Essentials;
// 存储字符串值
Preferences.Set("username", "Alice");
// 存储整数值
Preferences.Set("age", 25);
// 存储布尔值
Preferences.Set("isLoggedIn", true);
// 获取字符串值
string username = Preferences.Get("username", "defaultUser");
// 获取整数值
int age = Preferences.Get("age", 0);
// 获取布尔值
bool isLoggedIn = Preferences.Get("isLoggedIn", false);
Preferences.Remove("username");
Preferences.Clear();
// 从 Preferences 中获取用户信息,如果没有找到则返回空字符串
string Username = Preferences.Get("Username", string.Empty);
string Password = Preferences.Get("Password", string.Empty);
List / Split
List<string> list_inter = new List<string>();
// ["Hoo | Jely | Muyi | Noma"]
string[] str = movie_data.Genre.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
list_inter.AddRange(str);
// ["Hoo","Jely","Muyi","Noma"]
Back End
public CalendarPopup(Show db)
{
InitializeComponent();
showdb = db
var movie_db = Moviedb_Detail.GetAllMovie();
var movie_data = movie_db.Where(x => x.MovieID == db.MovieID).FirstOrDefault();
MovieName.Text = movie_data.Title;
DateText.Text = db.Date.ToString().Substring(0, 10);
Time.Text = $"{db.StartTime} - {db.EndTime}";
}
XAML View
我的 Sakura Cinama
项目首页的代码,采用了 MVVM
方式来获取 API
数据。