Jean-Daniel Gasser
Jean-Daniel Gasser

Reputation: 532

Xamarin Forms: attach behavior to all controls of same type in XAML

Is it possible to attach a certain behavior to all controls of a certain type in Xamarin Forms?

I know it is possible to assign properties to certain types of controls using styles in App.xaml <ResourceDictionary>.

Is it possible to do the same with behaviors?

I tried this code:

<Style TargetType="ImageButton">
  <Setter Property="Behaviors" Value="{StaticResource DeactivatableButton}"/>
</Style>

But running it throws the following exception:

System.InvalidOperationException: 'The BindableProperty "Behaviors" is readonly.'

Upvotes: 0

Views: 405

Answers (1)

Jai Gupta
Jai Gupta

Reputation: 1414

Please see this reference

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/behaviors/creating

public class NumericValidationBehavior : Behavior<Entry>
{
    public static readonly BindableProperty AttachBehaviorProperty =
        BindableProperty.CreateAttached ("AttachBehavior", typeof(bool), typeof(NumericValidationBehavior), false, propertyChanged: OnAttachBehaviorChanged);

    public static bool GetAttachBehavior (BindableObject view)
    {
        return (bool)view.GetValue (AttachBehaviorProperty);
    }

    public static void SetAttachBehavior (BindableObject view, bool value)
    {
        view.SetValue (AttachBehaviorProperty, value);
    }

    static void OnAttachBehaviorChanged (BindableObject view, object oldValue, object newValue)
    {
        var entry = view as Entry;
        if (entry == null) {
            return;
        }

        bool attachBehavior = (bool)newValue;
        if (attachBehavior) {
            entry.Behaviors.Add (new NumericValidationBehavior ());
        } else {
            var toRemove = entry.Behaviors.FirstOrDefault (b => b is NumericValidationBehavior);
            if (toRemove != null) {
                entry.Behaviors.Remove (toRemove);
            }
        }
    }
    ...
}

Style

<Style x:Key="NumericValidationStyle" TargetType="Entry">
    <Style.Setters>
        <Setter Property="local:NumericValidationBehavior.AttachBehavior" Value="true" />
    </Style.Setters>
</Style>

xaml

<Entry Placeholder="Enter a value" Style="{StaticResource NumericValidationStyle}">

Upvotes: 1

Related Questions