Xamarin.Forms のトリガーXamarin.Forms Triggers
サンプルのダウンロード
Download the sample
トリガーを使用すると、イベントまたはプロパティの変更に基づいてコントロールの外観を変更するアクションを XAML での宣言として表すことができます。Triggers allow you to express actions declaratively in XAML that change the appearance of controls based on events or property changes.
トリガーは、コントロールに直接割り当てることも、ページ レベルまたはアプリケーション レベルのリソース ディクショナリに追加して複数のコントロールに適用することもできます。You can assign a trigger directly to a control, or add it to a page-level or app-level resource dictionary to be applied to multiple controls.
4 種類のトリガーがあります。There are four types of trigger:
プロパティ トリガー -コントロールのプロパティが特定の値に設定されると発生します。Property Trigger - occurs when a property on a control is set to a particular value.
データ トリガー - データ バインディングを使用し、別のコントロールのプロパティに基づいてトリガーします。Data Trigger - uses data binding to trigger based on the properties of another control.
イベント トリガー -コントロールでイベントが発生すると発生します。Event Trigger - occurs when an event occurs on the control.
マルチ トリガー - アクションが発生する前に、複数のトリガー条件を設定できます。Multi Trigger - allows multiple trigger conditions to be set before an action occurs.
プロパティ トリガーProperty Triggers
コントロールのトリガー コレクションに Trigger
要素を追加して、XAML 内だけでシンプルなトリガーを表現できます。A simple trigger can be expressed purely in XAML, adding a Trigger
element to a control's triggers collection.
次の例では、フォーカスが設定されると背景色を Entry
に変更するトリガーを示します。This example shows a trigger that changes an Entry
background color when it receives focus:
<Entry Placeholder="enter name">
<Entry.Triggers>
<Trigger TargetType="Entry"
Property="IsFocused" Value="True">
<Setter Property="BackgroundColor" Value="Yellow" />
</Trigger>
</Entry.Triggers>
</Entry>
トリガーの宣言の重要な部分は次のとおりです。The important parts of the trigger's declaration are:
TargetType - トリガーを適用するコントロールの種類です。TargetType - the control type that the trigger applies to.
Property - コントロール上で監視するプロパティです。Property - the property on the control that is monitored.
Value - 監視対象のプロパティがこの値になったら、トリガーをアクティブにします。Value - the value, when it occurs for the monitored property, that causes the trigger to activate.
Setter - トリガー条件が満たされたときの
Setter
要素のコレクションを追加できます。Setter - a collection ofSetter
elements can be added and when the trigger condition is met. 設定するには、Property
とValue
を指定する必要があります。You must specify theProperty
andValue
to set.EnterActions と ExitActions (示されていません) - コードで記述され、
Setter
要素に加えて (または代えて) 使用できます。EnterActions and ExitActions (not shown) - are written in code and can be used in addition to (or instead of)Setter
elements. これらについては、後で説明します。They are described below.
スタイルを使用してトリガーを適用するApplying a Trigger using a Style
トリガーは、コントロール、ページ、またはアプリケーションの ResourceDictionary
の Style
宣言に追加することもできます。Triggers can also be added to a Style
declaration on a control, in a page, or an application ResourceDictionary
. 次の例では、暗黙のスタイルを宣言しています (つまり、Key
が設定されていません)。これは、ページ上のすべての Entry
コントロールに適用されることを意味します。This example declares an implicit style (ie. no Key
is set) which means it will apply to all Entry
controls on the page.
<ContentPage.Resources>
<ResourceDictionary>
<Style TargetType="Entry">
<Style.Triggers>
<Trigger TargetType="Entry"
Property="IsFocused" Value="True">
<Setter Property="BackgroundColor" Value="Yellow" />
</Trigger>
</Style.Triggers>
</Style>
</ResourceDictionary>
</ContentPage.Resources>
データ トリガーData Triggers
データ トリガーでは、データ バインディングを使用して別のコントロールが監視され、Setter
が呼び出されます。Data triggers use data binding to monitor another control to cause the Setter
s to get called. プロパティ トリガーでの Property
属性の代わりに、指定した値を監視する Binding
属性を設定します。Instead of the Property
attribute in a property trigger, set the Binding
attribute to monitor for the specified value.
次の例では、データ バインディング構文 {Binding Source={x:Reference entry}, Path=Text.Length}
を使用していますThe example below uses the data binding syntax {Binding Source={x:Reference entry}, Path=Text.Length}
これは、別のコントロールのプロパティを参照する方法です。which is how we refer to another control's properties. entry
の長さが 0 の場合、トリガーがアクティブにされます。When the length of the entry
is zero, the trigger is activated. このサンプルでは、入力が空の場合、トリガーでボタンが無効にされます。In this sample the trigger disables the button when the input is empty.
<!-- the x:Name is referenced below in DataTrigger-->
<!-- tip: make sure to set the Text="" (or some other default) -->
<Entry x:Name="entry"
Text=""
Placeholder="required field" />
<Button x:Name="button" Text="Save"
FontSize="Large"
HorizontalOptions="Center">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Source={x:Reference entry},
Path=Text.Length}"
Value="0">
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Button.Triggers>
</Button>
ヒント
Path=Text.Length
を評価するときは常に、ターゲット プロパティの既定値が提供されます (例:When evaluating Path=Text.Length
always provide a default value for the target property (eg. Text=""
)。そうしないと null
になって、トリガーが意図したとおりに動作しないためです。Text=""
) because otherwise it will be null
and the trigger won't work like you expect.
Setter
を指定するだけでなく、EnterActions
と ExitActions
を提供することもできます。In addition to specifying Setter
s you can also provide EnterActions
and ExitActions
.
Event TriggersEvent Triggers
次の例での "Clicked"
のように、EventTrigger
要素では Event
プロパティのみが必要です。The EventTrigger
element requires only an Event
property, such as "Clicked"
in the example below.
<EventTrigger Event="Clicked">
<local:NumericValidationTriggerAction />
</EventTrigger>
Setter
要素はなく、代わりにページの XAML で xmlns:local
が宣言されている必要のある local:NumericValidationTriggerAction
によって定義されたクラスへの参照があることに注意してください。Notice that there are no Setter
elements but rather a reference to a class defined by local:NumericValidationTriggerAction
which requires the xmlns:local
to be declared in the page's XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:WorkingWithTriggers;assembly=WorkingWithTriggers"
クラス自体では TriggerAction
が実装されています。これは、トリガー イベントが発生するたびに呼び出される Invoke
メソッドに対するオーバーライドを提供する必要があることを意味します。The class itself implements TriggerAction
which means it should provide an override for the Invoke
method that is called whenever the trigger event occurs.
トリガー アクションは次のように実装する必要があります。A trigger action implementation should:
トリガーの適用対象であるコントロールの種類に対応するジェネリック パラメーターを使用してジェネリック
TriggerAction<T>
クラスを実装します。Implement the genericTriggerAction<T>
class, with the generic parameter corresponding with the type of control the trigger will be applied to.VisualElement
のようなスーパークラスを使用してさまざまなコントロールで動作するトリガーを記述したり、Entry
のようなコントロールの種類を指定したりできます。You can use superclasses such asVisualElement
to write trigger actions that work with a variety of controls, or specify a control type likeEntry
.Invoke
メソッドをオーバーライドします。これは、トリガー条件が満たされるたびに呼び出されます。Override theInvoke
method - this is called whenever the trigger criteria are met.必要に応じて、トリガーを宣言するときに XAML で設定できるプロパティを公開します。Optionally expose properties that can be set in the XAML when the trigger is declared. この例については、付属のサンプル アプリケーションの
VisualElementPopTriggerAction
クラスを参照してください。For an example of this, see theVisualElementPopTriggerAction
class in the accompanying sample application.
public class NumericValidationTriggerAction : TriggerAction<Entry>
{
protected override void Invoke (Entry entry)
{
double result;
bool isValid = Double.TryParse (entry.Text, out result);
entry.TextColor = isValid ? Color.Default : Color.Red;
}
}
これにより、イベント トリガーを XAML から使用できるようになります。The event trigger can then be consumed from XAML:
<EventTrigger Event="TextChanged">
<local:NumericValidationTriggerAction />
</EventTrigger>
ResourceDictionary
でトリガーを共有する場合は注意が必要です。コントロール間で 1 つのインスタンスが共有されるので、1 つで構成された状態がすべてに適用されます。Be careful when sharing triggers in a ResourceDictionary
, one instance will be shared among controls so any state that is configured once will apply to them all.
イベント トリガーでは、後で説明する EnterActions
と ExitActions
がサポートされていないことに注意してください。Note that event triggers do not support EnterActions
and ExitActions
described below.
マルチ トリガーMulti Triggers
MultiTrigger
は Trigger
や DataTrigger
と似ていますが、複数の条件を使用できる点が異なります。A MultiTrigger
looks similar to a Trigger
or DataTrigger
except there can be more than one condition. Setter
がトリガーされるには、すべての条件が満たされる必要があります。All the conditions must be true before the Setter
s are triggered.
2 つの異なる入力 (email
と phone
) にバインドされているボタンに対するトリガーの例を次に示します。Here's an example of a trigger for a button that binds to two different inputs (email
and phone
):
<MultiTrigger TargetType="Button">
<MultiTrigger.Conditions>
<BindingCondition Binding="{Binding Source={x:Reference email},
Path=Text.Length}"
Value="0" />
<BindingCondition Binding="{Binding Source={x:Reference phone},
Path=Text.Length}"
Value="0" />
</MultiTrigger.Conditions>
<Setter Property="IsEnabled" Value="False" />
<!-- multiple Setter elements are allowed -->
</MultiTrigger>
Conditions
コレクションには、次のように PropertyCondition
要素を含めることもできます。The Conditions
collection could also contain PropertyCondition
elements like this:
<PropertyCondition Property="Text" Value="OK" />
"すべて必要" マルチ トリガーの作成Building a "require all" multi trigger
マルチ トリガーでは、すべての条件が真のときにのみコントロールが更新されます。The multi trigger only updates its control when all conditions are true. "すべてのフィールドの長さが 0" であることをテストするのは (すべての入力が完了する必要のあるログイン ページなど)、簡単ではありません。"Text.Length > 0 の場合" という条件が必要ですが、XAML でこれを表現することができないためです。Testing for "all field lengths are zero" (such as a login page where all inputs must be complete) is tricky because you want a condition "where Text.Length > 0" but this can't be expressed in XAML.
これは、IValueConverter
を使用して行うことができます。This can be done with an IValueConverter
. 次のコンバーター コードでは、Text.Length
のバインドが、フィールドが空かどうかを示す bool
に変換されています。The converter code below transforms the Text.Length
binding into a bool
that indicates whether a field is empty or not:
public class MultiTriggerConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if ((int)value > 0) // length > 0 ?
return true; // some data has been entered
else
return false; // input is empty
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotSupportedException ();
}
}
このコンバーターをマルチ トリガーで使用するには、最初に、ページのリソース ディクショナリに追加します (カスタム xmlns:local
名前空間の定義と共に)。To use this converter in a multi trigger, first add it to the page's resource dictionary (along with a custom xmlns:local
namespace definition):
<ResourceDictionary>
<local:MultiTriggerConverter x:Key="dataHasBeenEntered" />
</ResourceDictionary>
XAML を以下に示します。The XAML is shown below. 最初のマルチ トリガーの例と次の点が異なることに注意してください。Note the following differences from the first multi trigger example:
- ボタンには、
IsEnabled="false"
が既定で設定されます。The button hasIsEnabled="false"
set by default. - マルチ トリガーの条件では、コンバーターを使用して
Text.Length
の値がboolean
に変換されます。The multi trigger conditions use the converter to turn theText.Length
value into aboolean
. - すべての条件が
true
の場合、セッターはボタンのIsEnabled
プロパティをtrue
にします。When all the conditions aretrue
, the setter makes the button'sIsEnabled
propertytrue
.
<Entry x:Name="user" Text="" Placeholder="user name" />
<Entry x:Name="pwd" Text="" Placeholder="password" />
<Button x:Name="loginButton" Text="Login"
FontSize="Large"
HorizontalOptions="Center"
IsEnabled="false">
<Button.Triggers>
<MultiTrigger TargetType="Button">
<MultiTrigger.Conditions>
<BindingCondition Binding="{Binding Source={x:Reference user},
Path=Text.Length,
Converter={StaticResource dataHasBeenEntered}}"
Value="true" />
<BindingCondition Binding="{Binding Source={x:Reference pwd},
Path=Text.Length,
Converter={StaticResource dataHasBeenEntered}}"
Value="true" />
</MultiTrigger.Conditions>
<Setter Property="IsEnabled" Value="True" />
</MultiTrigger>
</Button.Triggers>
</Button>
次のスクリーンショットは、上記の 2 つのマルチ トリガーの例の違いを示したものです。These screenshots show the difference between the two multi trigger examples above. 画面の上部では、 [Save] ボタンを有効にするには、1 つの Entry
へのテキスト入力だけで十分です。In the top part of the screens, text input in just one Entry
is enough to enable the Save button.
画面の下部では、両方のフィールドにデータを入力するまで、 [Login] ボタンはアクティブになりません。In the bottom part of the screens, the Login button remains inactive until both fields contain data.
EnterActions と ExitActionsEnterActions and ExitActions
トリガーが発生したときの変更を実装するもう 1 つの方法は、EnterActions
および ExitActions
コレクションを追加して、TriggerAction<T>
の実装を指定することです。Another way to implement changes when a trigger occurs is by adding EnterActions
and ExitActions
collections and specifying TriggerAction<T>
implementations.
EnterActions
コレクションは、トリガー条件が満たされると呼び出される TriggerAction
オブジェクトの IList
を定義するのに使用されます。The EnterActions
collection is used to define an IList
of TriggerAction
objects that will be invoked when the trigger condition is met. ExitActions
コレクションは、トリガー条件が満たされなくなったら呼び出される TriggerAction
オブジェクトの IList
を定義するのに使用されます。The ExitActions
collection is used to define an IList
of TriggerAction
objects that will be invoked after the trigger condition is no longer met.
注意
EnterActions
コレクションと ExitActions
コレクションで定義されている TriggerAction
オブジェクトは、EventTrigger
クラスによって無視されます。The TriggerAction
objects defined in the EnterActions
and ExitActions
collections are ignored by the EventTrigger
class.
トリガーで Setter
と共に EnterActions
と ExitActions
の "両方" を提供できますが、Setter
はすぐに呼び出されることに注意してください (EnterAction
または ExitAction
が完了するのを待機しません)。You can provide both EnterActions
and ExitActions
as well as Setter
s in a trigger, but be aware that the Setter
s are called immediately (they do not wait for the EnterAction
or ExitAction
to complete). 代わりに、コードですべてを実行し、Setter
をまったく使用しないこともできます。Alternatively you can perform everything in the code and not use Setter
s at all.
<Entry Placeholder="enter job title">
<Entry.Triggers>
<Trigger TargetType="Entry"
Property="Entry.IsFocused" Value="True">
<Trigger.EnterActions>
<local:FadeTriggerAction StartsFrom="0"" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<local:FadeTriggerAction StartsFrom="1" />
</Trigger.ExitActions>
<!-- You can use both Enter/Exit and Setter together if required -->
</Trigger>
</Entry.Triggers>
</Entry>
例のごとく、XAML でクラスを参照するときは、次のように xmlns:local
などの名前空間を宣言する必要があります。As always, when a class is referenced in XAML you should declare a namespace such as xmlns:local
as shown here:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:WorkingWithTriggers;assembly=WorkingWithTriggers"
FadeTriggerAction
のコードを次に示します。The FadeTriggerAction
code is shown below:
public class FadeTriggerAction : TriggerAction<VisualElement>
{
public FadeTriggerAction() {}
public int StartsFrom { set; get; }
protected override void Invoke (VisualElement visual)
{
visual.Animate("", new Animation( (d)=>{
var val = StartsFrom==1 ? d : 1-d;
visual.BackgroundColor = Color.FromRgb(1, val, 1);
}),
length:1000, // milliseconds
easing: Easing.Linear);
}
}
関連リンクRelated Links
フィードバック
フィードバックを読み込んでいます...