How to create an async binding with a Delay property for Xamarin Forms

JerajoJerajo Member ✭✭

I have a binding on a Switch attribute IsToggled. I would like to have the ability to specify a delay time to prevent double clicks o double taps.
If there is not way to control how many times per second the **PageModel ** gets notify , I wold like to know how manage the OnItemPropertyChangedEvent to trigger after a Delay.

The Switch is inside of a ViewCell

XAML Snippet

<Switch IsToggled="{Binding IsChecked, Delay="300"}" />

I use a custom implementation of ObservableCollection<T> for the ViewCell Bindings.

PageModel

[AddINotifyPropertyChangedInterface]  // Using Fody
public class MainPageModel : FreshBasePageModel
{
    public MainPageModel(List<CheckTaskVieModel> dataModel)
    {
        var tasks = dataModel.Where(m => !m.IsChecked).ToList();
        var checkedTasks = dataModel.Where(m => m.IsChecked).ToList();

        Tasks = new FulyObservableCollection<CheckTaskVieModel>(tasks);
        CheckedTasks = new FulyObservableCollection<CheckTaskVieModel>(checkedTasks);

        // Set event for lists
        Tasks.ItemPropertyChanged += ItemPropertyChanged;
        CheckedTasks.ItemPropertyChanged += ItemPropertyChanged;
    }

    public FulyObservableCollection<CheckTaskVieModel> Tasks { get; set; }
    public FulyObservableCollection<CheckTaskVieModel> CheckedTasks { get; set; }

    private async void ItemPropertyChanged(object sender, ItemPropertyChangedEventArgs e)
    {
        // Return if property name isn't IsChecked
        if (e.PropertyName != "IsChecked") return;

        var items = sender as IEnumerable<CheckTaskVieModel>;
        var item = (items).ToList()[e.CollectionIndex];

        if (item == null || item?.IsAnimating == true) return;

        item.IsAnimating = true; // The event gets call twice before this value gets true

        await Task.Delay(TimeSpan.FromMilliseconds(200));

        if (item.IsChecked)
        {
            Tasks.Remove(item);
            CheckedTasks.Add(newItem);
        }
        else
        {
            CheckedTasks.Remove(item);
            Tasks.Add(newItem);
        }

    }
}

How can I make a custom async Binding with an attribute TimeSpan Delay if is possible? or is there other approach to do what I want?.

Best Answer

Answers

  • JerajoJerajo Member ✭✭

    Thanks @ClintStLaurent. I think is easier to do what you suggest. 👍

Sign In or Register to comment.