為 Entry 控制元件新增特定於平臺的效果
- 使用 PCL 檔案建立一個新的 Xamarin Forms 應用程式 - >新解決方案 - >多平臺應用程式 - > Xamarin Forms - > Forms App; 將專案命名為
EffectsDemo
- 在 iOS 專案下,新增一個繼承
PlatformEffect
類的新Effect
類並覆蓋方法OnAttached
,OnDetached
和OnElementPropertyChanged
注意ResolutionGroupName
和ExportEffect
這兩個屬性,這些屬性是從 PCL /共享專案中消耗此效果所必需的。
-
OnAttached
是定製邏輯進入的方法 -
OnDetached
是清理和取消註冊的方法 -
OnElementPropertyChanged
是在不同元素的屬性變化時觸發的方法。要確定正確的屬性,請檢查確切的屬性更改並新增邏輯。在這個例子中,OnFocus
將提供Blue
顏色,OutofFocus
將提供Red
顏色using System; using EffectsDemo.iOS; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ResolutionGroupName("xhackers")] [assembly: ExportEffect(typeof(FocusEffect), "FocusEffect")] namespace EffectsDemo.iOS { public class FocusEffect : PlatformEffect { public FocusEffect() { } UIColor backgroundColor; protected override void OnAttached() { try { Control.BackgroundColor = backgroundColor = UIColor.Red; } catch (Exception ex) { Console.WriteLine("Cannot set attacked property" + ex.Message); } } protected override void OnDetached() { throw new NotImplementedException(); } protected override void OnElementPropertyChanged(System.ComponentModel.PropertyChangedEventArgs args) { base.OnElementPropertyChanged(args); try { if (args.PropertyName == "IsFocused") { if (Control.BackgroundColor == backgroundColor) { Control.BackgroundColor = UIColor.Blue; } else { Control.BackgroundColor = backgroundColor; } } } catch (Exception ex) { Console.WriteLine("Cannot set property " + ex.Message); } }
}}
-
要在應用程式中使用此效果,在
PCL
專案下,建立一個名為FocusEffect
的新類,它繼承自RoutingEffect
。這對於使 PCL 例項化特定於平臺的效果實現至關重要。示例程式碼如下:using Xamarin.Forms; namespace EffectsDemo { public class FocusEffect : RoutingEffect { public FocusEffect() : base("xhackers.FocusEffect") { } } }
-
將效果新增到 XAML 中的
Entry
控制元件<?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:local="clr-namespace:EffectsDemo" x:Class="EffectsDemo.EffectsDemoPage"> <StackLayout Orientation="Horizontal" HorizontalOptions="Center" VerticalOptions="Center"> <Label Text="Effects Demo" HorizontalOptions="StartAndExpand" VerticalOptions="Center" ></Label> <Entry Text="Controlled by effects" HorizontalOptions="FillAndExpand" VerticalOptions="Center"> <Entry.Effects> <local:FocusEffect> </local:FocusEffect> </Entry.Effects> </Entry> </StackLayout> </ContentPage>
https://i.stack.imgur.com/96stB.gif
https://i.stack.imgur.com/dDDuY.gif
由於效果僅在 iOS 版本中實現,當應用程式在 iOS Simulator
中執行時聚焦 Entry
背景顏色更改並且沒有任何事情發生在 Android Emulator
,因為 Effect
未在 Droid
專案下建立