You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Xamarin项目中用同一点赞按钮完成点赞并移除屏幕活动项

实现方案

要实现点赞后移除活动的需求,根据你的使用场景分两种处理方式:

场景1:当前为活动详情页,移除后返回活动列表页

你需要先通知上一级的活动列表页删除对应活动,再关闭当前详情页,推荐用MessagingCenter实现跨页面消息传递:

  1. 将活动列表页的数据源替换为ObservableCollection<Event>,它实现了集合变更通知接口,数据增减时会自动刷新UI,不要使用普通List作为数据源。
  2. 修改likeButton_Clicked方法,点赞接口调用成功后发送移除消息、关闭页面:
private async void likeButton_Clicked(object sender, EventArgs e)
{
    // 新增:避免重复点赞
    if (event1.LikeTrueFalse == "True")
    {
        await DisplayAlert("", "该活动你已经点过赞啦", "Ok");
        return;
    }

    var likedEvent = new Result()
    {
        Name = LblEventName.Text,
        UserId = Preferences.Get("userId", 0),
        LikeTrueFalse = "True"
    };

    var response = await ApiService.LikedEvents(likedEvent);
    if (response)
    {
        await DisplayAlert("", "活动点赞成功", "Ok");
        // 更新本地活动点赞状态
        event1.LikeTrueFalse = "True";
        // 发送消息通知列表页移除当前活动,参数为活动ID
        MessagingCenter.Send(this, "EventLiked", event1.Id);
        // 关闭当前详情页
        await Navigation.PopModalAsync();
    }
    else
    {
        await DisplayAlert("出错了", "操作失败,请稍后重试", "取消");
    }
}
  1. 在活动列表页添加消息订阅,收到消息后移除对应活动,记得页面销毁时取消订阅避免内存泄漏:
// 列表页数据源,需定义为类的全局属性
private ObservableCollection<Event> _eventList;

public EventListPage()
{
    InitializeComponent();
    _eventList = new ObservableCollection<Event>();
    // 绑定列表数据源
    MyEventsListView.ItemsSource = _eventList;

    // 订阅点赞成功的消息
    MessagingCenter.Subscribe<MatchDetail, int>(this, "EventLiked", (sender, eventId) =>
    {
        // 找到对应活动并移除
        var targetEvent = _eventList.FirstOrDefault(e => e.Id == eventId);
        if (targetEvent != null)
        {
            _eventList.Remove(targetEvent);
        }
    });
}

protected override void OnDisappearing()
{
    base.OnDisappearing();
    // 取消订阅,避免内存泄漏
    MessagingCenter.Unsubscribe<MatchDetail, int>(this, "EventLiked");
}

场景2:多个活动卡片直接排列在当前页面

给当前活动最外层的StackLayout设置名称x:Name="EventRootLayout",点赞成功后直接隐藏或者移除该布局即可:

// 直接隐藏布局
EventRootLayout.IsVisible = false;

// 或者从父容器彻底移除
((Layout)EventRootLayout.Parent).Children.Remove(EventRootLayout);

替代方案

如果不想使用MessagingCenter,也可以在活动列表页的OnAppearing生命周期方法里重新拉取最新的活动列表数据,直接刷新整个列表,逻辑更简单,只是会多一次接口请求。

内容的提问来源于stack exchange,提问作者aaaxii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 09:57:03