Xamarin.Forms button in ViewCell. How to handle the event?

后端 未结 1 893
生来不讨喜
生来不讨喜 2021-02-07 16:21

I have a custom ViewCell with a button. When I click this button I would like to handle this click in the ContentPage which displays the ListView with the ViewCells. In iOS, I w

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 17:04

    If you are using a view model or some other class, you can pass it into your cell and make your calls from there. The list view also currently overrides the buttons on your cell with the ItemSelected event from the list view. Luckily they put in an override on the data template.

    private readonly ViewModel _model;
    public CustomCell (ViewModel model)
    {
        _model = model; <--- Your DI foo
        BindingContext = model; <---
    
        button = new Button ();
    
        button.Text = "Add";
        button.VerticalOptions = LayoutOptions.Center;
    
        button.Clicked += (sender, args) => _model.DoSomething(); <---- Your action
    
        var nameLabel = new Label ();
        nameLabel.SetBinding (Label.TextProperty, "name");
        nameLabel.HorizontalOptions = LayoutOptions.FillAndExpand;
        nameLabel.VerticalOptions = LayoutOptions.Center;
    
        var viewLayout = new StackLayout () {
            Padding = new Thickness (10, 0, 10, 0),
            Orientation = StackOrientation.Horizontal,
            Children = { nameLabel, button }
        };
    
        View = viewLayout;
    }
    

    Then you can pass your class/view model into your cell with an anonymous function.

    ListView.ItemTemplate = new DataTemplate (() => new CustomCell(viewModel));
    

    This way you can trigger your event from the view cell, and handle it somewhere else (view model).

    0 讨论(0)
提交回复
热议问题