Skip to content

Instantly share code, notes, and snippets.

@ozzieperez
Last active February 3, 2017 14:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ozzieperez/b44a93d2f6cac83c69a0 to your computer and use it in GitHub Desktop.
Save ozzieperez/b44a93d2f6cac83c69a0 to your computer and use it in GitHub Desktop.
Xamarin.Forms Trigger Example
// Visual elements can react to events or property changes.
// Triggers can be thought of for "conditional styles".
// Types: Trigger, EventTrigger, DataTrigger, MultiTrigger
//EXAMPLE: hooking trigger to a property
//You have a trigger that fires when a property changes
//create the trigger
var trigger = new Trigger(typeof(Entry));
trigger.Property = Entry.IsFocusedProperty; // hooked to the "IsFocused" property!
trigger.Value = true; //if it's true...
trigger.Setters.Add(new Setter {Property = Entry.ScaleProperty, Value = 1.5});
//add the trigger to an element
var entry = new Entry{ Placeholder = "Enter name" };
entry.Triggers.Add(trigger);
//EXAMPLE: hooking trigger to an event
//Event triggers hook to events, instead of properties.
// You can add this to the OnTextChangedEvent of an Entry to turn text red if it's not numeric
public class NumericValidationTrigger : 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;
}
}
//DataTriggers can bind to OTHER controls, which is awesome for enabling buttons based on other controls' state.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment