如何在父标签页 xamarin 表单中更新徽章计数器 [英] How to update badge counter in Parent tab page xamarin forms

查看:68
本文介绍了如何在父标签页 xamarin 表单中更新徽章计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用标签页的应用程序,在父标签页的 xaml 中我填充了所有其他标签页,我有一个绑定到父标签页和其他每个标签页的视图模型的视图模型.我在其中一个标签上有一个徽章,上面有一个计数器,显示有多少消息.我在更新计数器时遇到问题.

I have a App that uses tabbed pages, In the xaml of the Parent tab page I populate all my other tab pages, I have a viewmodel that binds to the Parent tab page and viewmodels for each of the other Tab pages. I have a badge on one of the tabs that has a counter which shows how many messages there are. I am having trouble updating the counter.

所以我有一个调用来从数据库中检索未读消息的数量,这些消息在应用程序加载时填充到计数器中.当我导航查看消息时,它会更新消息已读取的数据库,然后我导航回带有 popasync 的选项卡式页面,然后我拉刷新执行调用以获取已读取的消息量但不更新计数器,如果我在 GetCounter 方法上放置一个断点,我会看到它正在以正确的数量更新计数器,但不会在徽章上更改.

So I have a call to retrieve the amount of unread messages from the database which is populating into the counter on app load. When i Navigate to view the message it updates the database of that the message has been read , I then navigate back to the tabbed page with a popasync , I then pull to refresh which executes the call to get amount of messages read but it not updating the the counter, if i put a break point on the GetCounter method i see it is updating the counter with the right amount but not changing in on the badge.

希望这是有道理的.

如果有人能帮忙,我将不胜感激.

If anyone can help i will be very grateful.

主标签页:

<NavigationPage Title="Message" Icon="email.png"  plugin:TabBadge.BadgeText="{Binding counter}" 
             plugin:TabBadge.BadgeColor="Red"
             plugin:TabBadge.BadgePosition="PositionTopRight"
             plugin:TabBadge.BadgeTextColor="Green">
    <x:Arguments>
        <local:MessagePage  BindingContext="{Binding messages}" />
    </x:Arguments>
</NavigationPage>



public partial class MasterTabPage : TabbedPage
{
    Master_PageViewModel vm;
    public MasterTabPage ()
    {
        InitializeComponent ();
        this.BindingContext = vm = new Master_PageViewModel(Navigation);
    }
}

主标签页视图模型:

 public class Master_PageViewModel : INotifyPropertyChanged
{
    INavigation Navigation;
    private int _counter;
    public int counter
    {
        get => _counter;
        set
        {
            _counter = value;
            OnPropertyChanged(nameof(counter));

        }
    }
    public MessagePageViewModel messages { get; set; }
    public Master_PageViewModel(INavigation navigation)
    {
        Navigation = navigation;
        messages = new MessagePageViewModel(Navigation);
        Init();
        counter = 0;
    }
    public async void Init()
    {
        await GetCounter();
    }
    public async Task GetCounter()
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                List<MessageModel> msg = new List<MessageModel>();

                using (HttpResponseMessage response = await client.GetAsync("http://localhost:53665/api/GetMessagesCount/Id=" + 2 + "/" ))
                {
                    if (response.IsSuccessStatusCode)
                    {
                        using (HttpContent content = response.Content)
                        {
                            var textresponse = await content.ReadAsStringAsync();
                            var json = JsonConvert.DeserializeObject<List<MessageModel>>(textresponse);
                            foreach (var i in json)
                            {
                                msg.Add(new MessageModel
                                {
                                    msgCounter = i.msgCounter,
                                });
                            }
                            counter = msg[0].msgCounter;
                        }
                    }
                    else
                    {

                    }
                }
            }
        }
        catch (Exception)
        {

        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

消息选项卡视图模型:

public class MessagePageViewModel : BaseViewModel
{

    public ICommand MessageDetailsCommand { get; set; }
    INavigation Navigation;

    private ObservableCollection<MessageModel> _messagesList;
    public ObservableCollection<MessageModel> MessagesList
    {
        get { return _messagesList; }
        set
        {
            if (_messagesList != value)
            {
                _messagesList = value;
            }
        }
    }

    public ICommand ReloadCommand { get; set; }
    public ICommand RefreshCommand
    {
        get
        {
            return new Command(async () =>
            {
                await GetMessages();
                Master_PageViewModel vm = new Master_PageViewModel(Navigation,multiMediaPickerService);
                await vm.GetCounter();
            });
        }
    }

    bool _isBusy;
    public bool IsBusy
    {
        get { return _isBusy; }
        set
        {
            _isBusy = value;

        }
    }
    public MessagePageViewModel(INavigation navigation)
    {


        ReloadCommand = new Command(async () => await ReloadPage());

        Navigation = navigation;
        MessageDetailsCommand = new Command(async (object obj) => await MessageDetails(obj));
        Initialize();

    }

    private async void Initialize()
    {

        await GetMessages();

    }

    private async Task ReloadPage()
    {
        await GetMessages();
    }


    public async Task GetMessages()
    {
        List<MessageModel> msg = new List<MessageModel>
           .........
        MessagesList = new ObservableCollection<MessageModel>(msg);

    }

    private async Task MessageDetails(object obj)
    {
        var item = (obj as MessageModel);

        await Navigation.PushAsync(new MessageDetailsPage(....));
    }

    }
    }
}

推荐答案

这是因为您在 RefreshCommand 中创建了 Master_PageViewModel 的新实例.它不是父标签页的绑定上下文,因此即使 GetCounter 已被触发,标签的标记也不会更新.

This is because you created a new instance of Master_PageViewModel in your RefreshCommand. It is not the parent tabbed page's binding context so the tab's badge won't be updated even though the GetCounter has been triggered.

您必须将父选项卡式视图模型传递给您的 MessagePageViewModel,例如:

You have to pass the parent tabbed view model to your MessagePageViewModel like:

public Master_PageViewModel(INavigation navigation)
{
    Navigation = navigation;
    messages = new MessagePageViewModel(Navigation, this);
    Init();
    counter = 0;
}

并更改您的消息页面视图模型的构造函数:

And change your message page view model's constructor:

Master_PageViewModel parentViewModel
public MessagePageViewModel(INavigation navigation, Master_PageViewModel viewModel)
{
    ReloadCommand = new Command(async () => await ReloadPage());

    Navigation = navigation;
    parentViewModel = viewModel;

    // ...
}

最后,触发刷新命令中的方法:

At last, trigger the method in your refresh command:

public ICommand RefreshCommand
{
    get
    {
        return new Command(async () =>
        {
            await GetMessages();
            await parentViewModel.GetCounter();
        });
    }
}

此外,我注意到您的 MessagePageViewModel 使用了父标签视图模型的导航.我认为这不是一个好方法,因为它有自己的 NavigationPage,因此它应该使用自己的导航而不是父导航.

Moreover, I noticed that your MessagePageViewModel used the parent tabbed view model's navigation. I don't think this is a good approach as it has its own NavigationPage so that it should utilize its own navigation instead of the parent's.

这篇关于如何在父标签页 xamarin 表单中更新徽章计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆