'Real-time QR update using Firebase
I've been making a project in Xamarin.Forms that use Firebase (which for now only saves items) to make a list.
I then retrieve and convert that list to string using IValueConverter, and I finally use that same string to convert it to QR code using ZXing.
In my code ItemViewPage.xaml, I used a CollectionView to check whether the database is updating in the first place.
My problem is that the QR code doesn't show until I remove and retype my binding in BarcodeValue during hot reload.
ItemViewPage.xaml:
<ContentPage.Resources>
<ResourceDictionary>
<local:CollectionConverter x:Key="CollectionConverter"/>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout>
<CollectionView ItemsSource="{Binding DatabaseItems}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Label Text="{Binding Product}" FontSize="Large"/>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<zxing:ZXingBarcodeImageView BarcodeValue="{Binding DatabaseItems, Converter={StaticResource CollectionConverter}}" WidthRequest="300" HeightRequest="300">
<zxing:ZXingBarcodeImageView.BarcodeOptions>
<zxingcommon:EncodingOptions Width="300" Height="300"/>
</zxing:ZXingBarcodeImageView.BarcodeOptions>
</zxing:ZXingBarcodeImageView>
</StackLayout>
</ContentPage.Content>
ItemViewPage.xaml.cs:
namespace InventorySample.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ItemViewPage : ContentPage
{
public ObservableCollection<MyDatabaseRecord> DatabaseItems { get; set; } = new
ObservableCollection<MyDatabaseRecord>();
readonly FirebaseClient firebaseClient = new FirebaseClient("https://inventorysample-eca49-default-rtdb.asia-southeast1.firebasedatabase.app/");
public ItemViewPage()
{
InitializeComponent();
BindingContext = this;
var collection = firebaseClient
.Child("Products")
.AsObservable<MyDatabaseRecord>()
.Subscribe((dbevent) =>
{
if(dbevent.Object != null)
{
DatabaseItems.Add(dbevent.Object);
}
});
}
}
}
CollectionConverter.cs
namespace InventorySample
{
public class CollectionConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ObservableCollection<MyDatabaseRecord> Items = (ObservableCollection<MyDatabaseRecord>)value;
var sb = new StringBuilder();
foreach (var item in Items)
{
sb.AppendLine(item.Product);
}
return sb.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
I've already tried multiple things and am completely stumped. Hope someone can help. Thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
