星期一, 8月 07, 2017

[X.Form] Event Trigger

根據這篇官方文章 Triggers 的練習

Event Trigger 說明
occurs when an event occurs on the control.
C#

需要建立一個 Class 繼承 TriggerAction<T> 且必須覆寫 invoke
namespace MVVMPractice
{
    public class NumericValidationTriggerAction : TriggerAction<Entry>
    {
        protected override void Invoke(Entry entry)
        {
            bool isValid = Double.TryParse(entry.Text, out double result);
            entry.TextColor = isValid ? Color.Green : Color.Red;
        }
    }
}
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"
             xmlns:local="clr-namespace:MVVMPractice"
             x:Class="MVVMPractice.XF3_EventTrigger">
    <ContentPage.Content>
        <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
            <Entry Placeholder="請輸入資料">
                <Entry.Triggers>
                   <EventTrigger Event="TextChanged">
                       <local:NumericValidationTriggerAction/>
                   </EventTrigger>
                </Entry.Triggers>
            </Entry>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
執行結果-1

[X.Form] EventTrigger-1

執行結果-2

[X.Form] EventTrigger-2

沒有留言:

張貼留言