Forum Xamarin.Forms

Custom behavior command not binding?

Joshua.R.RussoJoshua.R.Russo USUniversity ✭✭

I created the following behavior to capture the item appearing event

public class ListViewItemAppearingBehavior : Behavior<ListView>
    public static readonly BindableProperty CommandProperty =
        BindableProperty.Create("Command", typeof(ICommand), typeof(ListViewItemAppearingBehavior), null);

    public ICommand Command
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }

    protected override void OnAttachedTo(ListView bindable)
        bindable.ItemAppearing += OnListViewItemAppearing;

    protected override void OnDetachingFrom(ListView bindable)
        bindable.ItemAppearing -= OnListViewItemAppearing;
    private void OnListViewItemAppearing(object sender, ItemVisibilityEventArgs e)
        if (Command == null)

        if (Command.CanExecute(e.Item))



In my view I wired it up like so:

<ListView x:Name="DashboardList"    
          ItemsSource="{Binding DashboardItems}"
          SelectedItem="{Binding SelectedObject}"
          Header="{Binding .}"
          RefreshCommand="{Binding RefreshListCommand}"
          IsRefreshing="{Binding IsRefreshing}">
    <controls:Behaviors.ListViewItemAppearingBehavior Command="{Binding ListItemAppearingCommand}" />

Here's a sampling from my view model with the 2 commands from the view snippet above:

    private Command<object> _refreshListCommand;
    public Command<object> RefreshListCommand
            return _refreshListCommand ?? (_refreshListCommand = new Command<object>(RefreshListAction));

    private ICommand _listItemAppearingCommand;
    public ICommand ListItemAppearingCommand
            return _listItemAppearingCommand ?? (_listItemAppearingCommand = new Command<InnlightenObjectListItem>(ItemAppearingAction));

All of my other {Binding ...} calls hit the properties of their respective view model values except for this one. I put a break point in each of these 2 get statements and only the first one is hit.

I confirmed with break points that the behavior is loading and the event within the behavior is being fired.

Any thoughts on what I might be doing wrong with the Command binding?


  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    I would say that the BindingContext of your Behavior is not being set, as this bug describes.

    In this blog post, the section on Invoking a Command in Response to an Event shows how to do what you want, with sample code linked.

  • Joshua.R.RussoJoshua.R.Russo USUniversity ✭✭

    Awesome! Thank you! That was it!

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    Depends on your behavior. If you are looking to reuse the behavior, such as in a Style, Jason rightly points out that the current design is better for that.

Sign In or Register to comment.