Can I use Triggers from code?

Is there a way how I can use triggers from the code? I can't seem to find any examples. Basically I have some behaviors for my entries, and I want to trigger the Login Button's "IsVisible" property based on the 'IsValid' property from my entry's behavior:

    public class PEntry : Entry
        {
            public PEntry ()
                : base ()
            {
            }

            /// <summary>
            /// Determines whether this instance is valid.
            /// </summary>
            /// <returns><c>true</c> if this instance is valid; otherwise, <c>false</c>.</returns>
            public bool IsValid 
            {
                get{
                    // iterate through each entry's validator behaviors
                    foreach (var behavior in this.Behaviors) {
                        var validatorBehavior = behavior as IValidatorBehavior;
                        if (validatorBehavior != null) {
                            if (!validatorBehavior.IsValid) {
                                return false;
                            }
                        }
                    }

                    // default to true
                    return true;
                }
            }
        }

Posts

  • ShaunGrechShaunGrech USMember ✭✭

    Hi guys, anyone can help me out with this? I just need to find an example where I can use triggers from the code (not in XAML). This way if my textfield.IsValid status is false, I call the trigger.

    Thanks again
    Shaun

  • ArtemUstimovArtemUstimov RUMember ✭✭

    I think you doesn't need a trigger. This task can be solved in the next maner:

    var entry = new Entry(); var button = new Button(); button.BindingContext = entry; button.SetBinding (Button.IsVisibleProperty, "IsValid");

    So, if you sure you need a trigger, this can be done like this:
    var entry = new Entry(); var button = new Button(); button.BindingContext = entry; DataTrigger dataTrigger = new DataTrigger(typeof(Button)); dataTrigger.Binding = new Binding("IsValid"); dataTrigger.Value = true; dataTrigger.Setters.Add (new Setter { Property = Button.IsVisibleProperty, Value = true }); button.Triggers.Add (dataTrigger);

    For those who come from google.

  • ShaunGrechShaunGrech USMember ✭✭

    Hi Artem,

    Thank you for your reply. I like your initial answer however, imagine you have multiple fields (typical form) and they all have their validators. And you're binding the Button to 'IsValid', which 'IsValid' property is that?

    var nameEntry = new Entry();            
    var ageEntry = new Entry();
    var button = new Button();
    button.BindingContext = entry;
    button.SetBinding (Button.IsVisibleProperty, "IsValid");
    

    I want the button to be visible only when all the fields are Valid.

    Thanks
    Shaun

Sign In or Register to comment.