Custom Bindable Control issue with ICommand

Hi,
I'm creating a custom control. It is a simple horizonal list. As in many tutorials, I have created

    public static readonly BindableProperty SelectedCommandProperty =
        BindableProperty.Create("SelectedCommand", typeof(ICommand), typeof(HorizontalList), null);

    public ICommand SelectedCommand
    {
        get { return (ICommand)GetValue(SelectedCommandProperty); }
        set { SetValue(SelectedCommandProperty, value); }
    }

I also created an event called OnSelectedItemChanged: it is fired when a user tap on an image in the list. The implementation is

    private static void OnSelectedItemChanged(BindableObject bindable, object oldValue, object newValue)
    {
        var itemsView = (HorizontalList)bindable;
        if (newValue == oldValue && newValue != null)
        {
            return;
        }

        itemsView.SelectedItemChanged?.Invoke(itemsView, EventArgs.Empty);

        if (itemsView.SelectedCommand?.CanExecute(newValue) ?? false)
        {
            itemsView.SelectedCommand?.Execute(newValue);
        }
    }

In the XAML in my component I added this binding (SelectedItemChanged si for my test)

SelectedItemChanged="HorizontalList_SelectedItemChanged"
SelectedCommand="{Binding DetailCommand}"

When I tap on a item of the list, OnSelectedItemChanged is fired, Invoke is ok and the page receives the event, but itemsView.SelectedCommand is null.

I can't understand why. Could you help me? Thank you in advance

Answers

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭
        public static readonly BindableProperty SelectedCommandProperty =
            BindableProperty.Create("SelectedCommand", typeof(ICommand), typeof(HorizontalList), null);
    

    Default value for your command is null
    At that point you're screwed. Xamarin doesn't bind well to null. I fought round and round about that a couple years ago and it fell on deaf ears.

    Make the default a new command even if it does nothing. At least then it is a solid object with a memory address to point at. Later when you bind it to something you have a something to bind to.

    I've taken to never allowing any binded object to go to null. It always goes to a known default state object. A little more work but on the other hand you can never have a null reference exception.

  • EnricoRossiniEnricoRossini USMember ✭✭✭✭

    There are examples like in this post. The implementation is the same.

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    So you're saying you have examples, and you've done the same thing... So now you're good and the issue is resolved. Is that right?

Sign In or Register to comment.