I want to add badge counter to the navigation bar like in this tutorial.
https://www.xamboy.com/2018/03/08/adding-badge-to-toolbaritem-in-xamarin-forms/
This works great, but I am not satisfied that they created a method for displaying a badge instead of creating a bindable property "BadgeCounter" for toolbar item. So I decided to create this bindable property on my own.
Here is my code:
ExtendedToolbarItem.cs
using System;
using Todo.Helpers;
using Todo.Views;
using Xamarin.Forms;
namespace Todo.Controls
{
public class ExtendedToolbarItem : ToolbarItem
{
public static readonly BindableProperty BadgeCountProperty =
BindableProperty.Create(nameof(BadgeCount), typeof(int), typeof(ExtendedToolbarItem), 0, BindingMode.OneWay, propertyChanged: BadgeCountChanged);
public int BadgeCount
{
get => (int)GetValue(BadgeCountProperty);
set => SetValue(BadgeCountProperty, value);
}
private static void BadgeCountChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = bindable as ExtendedToolbarItem;
if (control == null) return;
DependencyService.Get<IToolbarItemBadge>().SetBadge((Page)control.Parent, control, newValue.ToString(), Color.Red, Color.White);
}
}
}
Then in the view
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Todo.Views.TodoItems"
xmlns:viewModels="clr-namespace:Todo.ViewModels"
xmlns:controls="clr-namespace:Todo.Controls"
Title="Things to do!">
<ContentPage.BindingContext>
<viewModels:TodoItemsViewModel />
</ContentPage.BindingContext>
<ContentPage.ToolbarItems>
<ToolbarItem Icon="plus.png" Command="{Binding AddItemCommand}"/>
<controls:ExtendedToolbarItem Icon="email.png" BadgeCount="{Binding UnreadMessages}"/>
</ContentPage.ToolbarItems>
And in the view model, you have to assign some value for "UnreadMessages".
This works great except for two cases.
I don't know why but when I am changing the orientation of the device (Android) the badge counter disappears. It also disappears when I am navigating back. It could be great if someone helps me solve this issue because that would a fantastic way to create a badge counter in Xamarin Forms - currently, there is no way to create it without creating a custom navbar.