如何在父选项卡页面xamarin表单中更新徽章计数器

时间:2019-06-06 18:46:39

标签: c# xamarin.forms mvvmcross badge

我有一个使用选项卡式页面的应用程序,位于“父级”选项卡页面的xaml中 我填充了所有其他标签页,我有一个绑定到“父”标签页的视图模型,以及其他每个标签页的视图模型。我在其中一个带有选项卡的选项卡上有一个徽章,该计数器显示有多少条消息。 我无法更新计数器。

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

希望如此。

如果有人可以帮助我,我将非常感激。

主标签页:

<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);
    }
}

主标签页ViewModel:

 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));
    }

消息标签ViewModel:

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(....));
    }

    }
    }
}

1 个答案:

答案 0 :(得分:2)

这是因为您在Master_PageViewModel中创建了RefreshCommand的新实例。它不是父选项卡页面的绑定上下文,因此即使触发了GetCounter,也不会更新选项卡的徽章。

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

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

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

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

    Navigation = navigation;
    parentViewModel = viewModel;

    // ...
}

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

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

此外,我注意到您的MessagePageViewModel使用了父级选项卡式视图模型的导航。我认为这不是一个好方法,因为它具有自己的NavigationPage,因此应该利用自己的导航而不是父级的导航。