Search code examples
c#xamllistviewdata-bindingxamarin

How do I use the BindingContext property of ViewCell in the XAML?


Hi I want to use the BindingContext property to bind different ViewCell to my Listview based on a certain condition

Here is the Xaml

<ListView>
    <ListView.ItemTemplate>
                  <DataTemplate>
                        <ViewCell BindingContext="??">//What do I do here?
                        </ViewCell>
                  </DataTemplate>
        </ListView.ItemTemplate>
 </ListView>

Here is are the classes for the ViewCells

    public class textViewCellNoContextActions : ViewCell
    {
        public textViewCellNoContextActions()
        {
            StackLayout layout = new StackLayout();
            layout.Padding = new Thickness(15, 0);
            Label label = new Label();

            label.SetBinding(Label.TextProperty, "ListItemTitle");
            layout.Children.Add(label);
            View = layout;
        }
    }

public class textViewCellWithContextActions : ViewCell
{
    public textViewCellWithContextActions()
    {
        StackLayout layout = new StackLayout();
        layout.Padding = new Thickness(15, 0);
        Label label = new Label();

        label.SetBinding(Label.TextProperty, "ListItemTitle");
        layout.Children.Add(label);

        var moreAction = new MenuItem { Text = "More" };
        moreAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
        moreAction.Clicked += OnMore;

        var deleteAction = new MenuItem { Text = "Delete", IsDestructive = true }; // red background
        deleteAction.SetBinding(MenuItem.CommandParameterProperty, new Binding("."));
        deleteAction.Clicked += OnDelete;

        this.ContextActions.Add(moreAction);
        this.ContextActions.Add(deleteAction);
        View = layout;
    }

In my ViewModel, I want to decide which ViewCell to bind to. How do I achieve this? Do I also need to use BindingContextChanged?


Solution

  • For what I wanted to achieve I did the following...

    In the XAML

    <ViewCell BindingContextChanged="OnBindingContextChanged">
    

    In the code behind

    private void OnBindingContextChanged(object sender, EventArgs e)
    {
        base.OnBindingContextChanged();
    
        if (BindingContext == null)
            return;
    
        ViewCell theViewCell = ((ViewCell)sender);
        var item = theViewCell.BindingContext as ListItemModel;
        theViewCell.ContextActions.Clear();
    
        if (item != null)
        {
            if (item.ListItemType == ListItemTypeEnum.FavoritePlaces
               || item.ListItemType == ListItemTypeEnum.FavoritePeople)
            {
                theViewCell.ContextActions.Add(new MenuItem()
                {
                    Text = "Delete"
                });
            }
        }
    }
    

    Based which type of list item we are dealing with, we get to decide where to place the context actions