XAML in Xamarin.Forms 基礎篇 電子書

XAML in Xamarin.Forms 基礎篇 電子書
XAML in Xamarin.Forms 基礎篇 電子書

Xamarin.Forms 快速入門 電子書

Xamarin.Forms 快速入門 電子書
Xamarin.Forms 快速入門 電子書

2020/04/06

使用 Xamarin.Plugin.SharedTransitions 製作出具有跨頁面之共用項目動畫效果

使用 Xamarin.Plugin.SharedTransitions 製作出具有跨頁面之共用項目動畫效果

最近觀看完 .NET Conf: Focus on Xamarin 的 Building Beautiful Apps with Xamarin.Forms 影片,頓時間覺得 Xamarin.Forms 似乎又進化了許多,在這個影片中我看到許多驚豔內容,對於 Xamarin.Plugin.SharedTransitions 這個套件所產生出來的效果,更讓我想要能夠親自來嘗試看看,因此,我先從 Xamarin.Forms-Monkeys 這裡取得許多猴子介紹的紀錄內容,並且將這些內容包裝到練習使用的 NuGet 套件內,接著,實做出如下面影片中的動畫效果。
這個說明專案的原始碼為 xfSharedTransitions

範例專案說明

在這個測試範例專案中,將會使用 Prism Template Pack 建立一個 Xamarin.Forms 的專案,接著要安裝 Xamarin.FFImageLoading.Forms & Xamarin.Plugin.SharedTransitions 這兩個 NuGet 套件;這裡會用到 Xamarin.FFImageLoading.Forms 這個套件,這是因為一開始建立這個測試專案的時候,使用的是 Xamarin.Forms 內的 Image 元件,不過,由於要顯示的猴子圖片是來自於 Internet 上,因此,當要進行頁面切換的時候,對於共用圖片元件的動畫動作,變得不自然與動畫路徑怪怪的,可是,若使用 GiampaoloGabba / Xamarin.Plugin.SharedTransitions 內提供的範例專案,卻可以正常運作,經過了解,發現到該範例專案內使用的貓狗圖片,都是專案內的圖片檔案,不是透過 Internet 方式取得的,所以,就根據該專案的說明內容,嘗試使用 Xamarin.FFImageLoading.Forms 這個元件,讓圖片從 Internet 下載下來,使用本機上快取的圖片檔案,發現到就可以順利運作。
首先,在 [MainPage.xaml] 檔案中,建立底下的 XAML 宣告
在這裡因為會使用到 amarin.FFImageLoading.Forms & Xamarin.Plugin.SharedTransitions 功能,因此,加入了兩個命名空間 sharedTransitions & ffimageloading
而在 ContentPage 內,也使用到兩個附加屬性,用來宣告動畫需要多久的時間,這裡使用 sharedTransitions:SharedTransitionNavigationPage.TransitionDuration="500" 來宣告需要花費 500ms,並且使用 sharedTransitions:SharedTransitionNavigationPage.TransitionSelectedGroup="{Binding SelectedMonkeyId}" 用於宣告點選了哪個集合項目中的紀錄,若僅是做兩個頁面之間的切換,並沒有牽扯到集合項目,例如 ListView,這裡是可以不用使用這個附加屬性哦。
<?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="xfSharedTransitions.Views.MainPage"
             xmlns:behavior="http://prismlibrary.com"
             xmlns:sharedTransitions="clr-namespace:Plugin.SharedTransitions;assembly=Plugin.SharedTransitions"
             xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
             sharedTransitions:SharedTransitionNavigationPage.TransitionDuration="500"
             sharedTransitions:SharedTransitionNavigationPage.TransitionSelectedGroup="{Binding SelectedMonkeyId}"
             Title="猴仔們">

    <Grid>
        <ListView
            HasUnevenRows="True"
            ItemsSource="{Binding AllMonkey}"
            SelectionMode="None"
            Footer="">
            <ListView.Behaviors>
                <behavior:EventToCommandBehavior
                    EventName="ItemTapped"
                    Command="{Binding MonkeyCommand}"
                    EventArgsParameterPath="Item"/>
            </ListView.Behaviors>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="50"/>
                                <RowDefinition Height="50"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="100"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>
                            <Label
                                Grid.Row="0" Grid.Column="1"
                                HorizontalOptions="Start" VerticalOptions="End"
                                FontSize="24"
                                Text="{Binding Name}"/>

                            <Label
                                Grid.Row="1" Grid.Column="1"
                                HorizontalOptions="Start" VerticalOptions="Start"
                                FontSize="16"
                                Text="{Binding Location}"/>
                            <ffimageloading:CachedImage HeightRequest="80"
                                                        Grid.Row="0" Grid.RowSpan="2"
                                                        Aspect="AspectFit"
                                                        Source="{Binding ImageUrl}"
                                                        sharedTransitions:Transition.Name="MonkeyImage"
                                                        sharedTransitions:Transition.Group="{Binding Id}"/>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>

        </ListView>
    </Grid>
</ContentPage>
在這裡因為會使用到 amarin.FFImageLoading.Forms & Xamarin.Plugin.SharedTransitions 功能,因此,加入了兩個命名空間 sharedTransitions & ffimageloading
而在 ContentPage 內,也使用到兩個附加屬性,用來宣告動畫需要多久的時間,這裡使用 sharedTransitions:SharedTransitionNavigationPage.TransitionDuration="500" 來宣告需要花費 500ms,並且使用 sharedTransitions:SharedTransitionNavigationPage.TransitionSelectedGroup="{Binding SelectedMonkeyId}" 用於宣告點選了哪個集合項目中的紀錄,若僅是做兩個頁面之間的切換,並沒有牽扯到集合項目,例如 ListView,這裡是可以不用使用這個附加屬性哦。
在 ItemsTemplate 內,需要使用 sharedTransitions:Transition.Name="MonkeyImage" 這樣的附加屬性宣告,指定兩個頁面都有的共同視覺項目,宣告這裡需要進行動畫的變化動作,而 sharedTransitions:Transition.Group="{Binding Id}" 則是同樣用於集合檢視內才會用到的宣告,這裡將會指定這筆紀錄的 ID 到 Group 屬性內,而這個屬性可以是整數或者是字串,不過,必須具有唯一值特性。
對 MainPage 的 ViewModel,將會使用底下的 C# 程式碼來設計
public class MainPageViewModel : INotifyPropertyChanged, INavigationAware
{
    public event PropertyChangedEventHandler PropertyChanged;

    private readonly INavigationService navigationService;
    public string Title { get; set; }
    public ObservableCollection<Monkey> AllMonkey { get; set; } = new ObservableCollection<Monkey>();
    public DelegateCommand<Monkey> MonkeyCommand { get; set; }
    public int SelectedMonkeyId { get; set; }
    public MainPageViewModel(INavigationService navigationService)
    {
        this.navigationService = navigationService;
        Title = MonkeyData.Monkeys.Count.ToString();
        MonkeyCommand = new DelegateCommand<Monkey>(async x =>
        {
            SelectedMonkeyId = x.Id;

            NavigationParameters para = new NavigationParameters();
            para.Add(nameof(Monkey), x);
            await Task.Delay(100);
            await navigationService.NavigateAsync(nameof(DetailPage), para);
        });
    }

    public void OnNavigatedFrom(INavigationParameters parameters)
    {
    }

    public void OnNavigatedTo(INavigationParameters parameters)
    {
        int idx = 1;
        foreach (var item in MonkeyData.Monkeys)
        {
            AllMonkey.Add(item);
            idx++;
        }
    }

    public void OnNavigatingTo(INavigationParameters parameters)
    {
    }

}
對於點選 ListView 的某個紀錄,將會觸發 MonkeyCommand 這個命令,從這個命令參數中,可以取得使用者所點選的物件值,在這裡,將會把所點選的紀錄物件值,透過導航參數的鍵值 Monkey 傳送到下個頁面去
對於要切換過去的頁面,這裡新增一個 DetailPage.xaml 頁面與 DetailPageViewModel.cs 這兩個檔案,其中,對於頁面部分,將會設計底下的 XAML 宣告內容
從這裡可以很清楚的看到,僅有在圖片檢視的地方,使用到 sharedTransitions:Transition.Name="MonkeyImage" 宣告,這是用來串接兩個頁面共用檢視的宣告方式。
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="http://prismlibrary.com"
             prism:ViewModelLocator.AutowireViewModel="True"
             xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
             xmlns:sharedTransitions="clr-namespace:Plugin.SharedTransitions;assembly=Plugin.SharedTransitions"
             x:Class="xfSharedTransitions.Views.DetailPage"
             Title="{Binding Monkey.Name, StringFormat='猴子:{0}'}"
             >

    <Grid>
        <ScrollView>
            <StackLayout Orientation="Vertical">
                <ffimageloading:CachedImage HeightRequest="300" WidthRequest="300"
                                                        Aspect="AspectFit"
                                                        Source="{Binding Monkey.ImageUrl}"
                                                        sharedTransitions:Transition.Name="MonkeyImage"
                                                        />
                <Label
                    HorizontalOptions="Center" VerticalOptions="End"
                    FontSize="24"
                    Text="{Binding Monkey.Name}"/>

                <Label
                    HorizontalOptions="Center" VerticalOptions="Start"
                    FontSize="16"
                    Text="{Binding Monkey.Location}"/>
                <Label
                    HorizontalOptions="Start" VerticalOptions="Start"
                    FontSize="14"
                    Text="{Binding Monkey.Details}"/>
            </StackLayout>
        </ScrollView>
    </Grid>
</ContentPage>




2020/04/05

在開發 Xamarin.Forms 專案的時候,可以讓 Android Emulator 模擬器存取本機 localhost ASP.NET Core Web API 服務的做法

在開發 Xamarin.Forms 專案的時候,可以讓 Android Emulator 模擬器存取本機 localhost ASP.NET Core Web API 服務的做法

當在進行 Xamarin.Forms 專案開發設計的時候,由於後端系統尚在開發過程中,因此,將會需要在本機來啟動這個開發中的 Web API 服務。
例如,當使用 ASP.NET Core 來開發出一個 Web API 專案,此時,若要存取這個專案所提供的 Web API 服務,就需要使用類似這樣的 URI https://localhost:5001/weatherforecast ,不過,從這個 URL 將會發現到,這個主機使用了 localhost ,使用 Xamarin.Forms 所開發出來的 Android 專案,將會在 Android Emulator 模擬器下來運行,此時,在 Android 模擬器下,對於這個 localhost 主機,將只會存取到本身模擬器內的 5001 埠,可是,這台 Android 模擬器內的 5001 埠內,並沒有任何 Web API 服務,該服務存在取當時開發主機的作業環境下。
在這篇文章中,將會嘗試提出一個解法 (當然,對於這樣的問題,是有其他不同的解決方法,大家可以想看看還有哪些方法呢?)
在此,請先建立一個 ASP.NET Core 的 Web API 專案
請打開 Startup.cs 檔案,為了將整個展示過程予以簡化,因此,將不會強制使用 HTTPS 這樣的協定,所以,找到 app.UseHttpsRedirection(); 敘述,將其註解起來。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    //app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
接著,在命令提示字元視窗內,輸入 ipconfig 命令,將會出現如下內容,這在這裡可以找到當前這台電腦中所使用 ip address,這裡將會看到 ip = 192.168.31.153
.
.
.
無線區域網路介面卡 Wi-Fi:

   連線特定 DNS 尾碼 . . . . . . . . :
   連結-本機 IPv6 位址 . . . . . . . : fe80::b975:1a80:f870:eb77%16
   IPv4 位址 . . . . . . . . . . . . : 192.168.31.153
   子網路遮罩 . . . . . . . . . . . .: 255.255.255.0
   預設閘道 . . . . . . . . . . . . .: 192.168.31.1
.
.
.
在這個 ASP.NET Core Web API 專案內,展開 Properties 節點,將會看到 launchSettings.json 這個檔案,請打開這個檔案。
找到 CoreLocalAPI 這個屬性,從該屬性內找到 applicationUrl 這個節點,將該節點值修正為 https://localhost:5001;http://localhost:5000;https://192.168.31.153:5001;http://192.168.31.153:5000
{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:63459",
      "sslPort": 44333
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "CoreLocalAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "weatherforecast",
      "applicationUrl": "https://localhost:5001;http://localhost:5000;https://192.168.31.153:5001;http://192.168.31.153:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
現在,可以使用命令提示字元視窗,切換到這個 API 專案所在的目錄下,並且輸入 dotnet run
如此,這個 Web API 專案便會在本機上開始執行了,從底下的啟動文字內容中,可以看到除了原先可以使用的 http://localhost:5000 URL 之外,還可以透過 http://192.168.31.153:5000 這個 URL 來連線到這 Web API 服務上。
Microsoft Windows [版本 10.0.18363.693]
(c) 2019 Microsoft Corporation. 著作權所有,並保留一切權利。

D:\Vulcan\Projects\CallLocakAPI\CoreLocalAPI>dotnet run
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://192.168.31.153:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://192.168.31.153:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\Vulcan\Projects\CallLocakAPI\CoreLocalAPI
因此,當在瀏覽器中輸入了 http://192.168.31.153:5000 URL 之後,將會看到底下的輸出內容
[{"date":"2020-03-10T12:21:44.4886014+08:00","temperatureC":-7,"temperatureF":20,"summary":"Mild"},{"date":"2020-03-11T12:21:44.4889745+08:00","temperatureC":44,"temperatureF":111,"summary":"Mild"},{"date":"2020-03-12T12:21:44.4889768+08:00","temperatureC":-19,"temperatureF":-2,"summary":"Hot"},{"date":"2020-03-13T12:21:44.488977+08:00","temperatureC":23,"temperatureF":73,"summary":"Scorching"},{"date":"2020-03-14T12:21:44.4889772+08:00","temperatureC":52,"temperatureF":125,"summary":"Balmy"}]
當確認 Web API 可以透過本機電腦的 WIFI IP 連線之後(不再僅需要透過 localhost 才能夠連線),現在可以來建立一個 Xamarin.Forms 的專案。
其中 View 的內容如下
<?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="CallLocakAPI.Views.MainPage"
             Title="{Binding Title}">

    <StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
        <Label Text="Welcome to Xamarin Forms and Prism!" />
        <Label Text="{Binding IP}" FontSize="16" TextColor="Blue"/>
        <Label Text="{Binding APIResult}" FontSize="14" TextColor="Red"/>
    </StackLayout>

</ContentPage>
而 ViewModel 的程式碼如下
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CallLocakAPI.ViewModels
{
    using System.ComponentModel;
    using System.Net.Http;
    using Localhost;
    using Prism.Events;
    using Prism.Navigation;
    using Prism.Services;
    using Xamarin.Essentials;

    public class MainPageViewModel : INotifyPropertyChanged, INavigationAware
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private readonly INavigationService navigationService;
        public string IP { get; set; }
        public string APIResult { get; set; }
        public MainPageViewModel(INavigationService navigationService)
        {
            this.navigationService = navigationService;

        }

        public void OnNavigatedFrom(INavigationParameters parameters)
        {
        }

        public async void OnNavigatedTo(INavigationParameters parameters)
        {
            IP = CrossLocalhost.Current.Ip;

            HttpClient client = new HttpClient();
            string result;
            try
            {
                APIResult = await client.GetStringAsync("http://192.168.31.153:5000/weatherforecast");

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

        public void OnNavigatingTo(INavigationParameters parameters)
        {
        }

    }
}
這個測試結果將會如下圖,從底下截圖的執行結果中可以看到這個 Android 模擬器當時使用 IP Address 為 10.0.2.2,而可以實際連線到本機電腦上跑的 Web API,並且得到執行結果。