I have 2 pages, one where I insert data into a Firebase database, let's call it Page2 and one where I display the Firebase Data, Page1.
I have a button click argument on Page2 where I insert data into the database but want to reload Page1 after this. It is structured like this (Page2.xaml.cs):
void btInsert_Clicked(System.Object sender, System.EventArgs e)
{
//Firebase connection
//Firebase data insertion
//Code to reload Page1
}
On my page 1 I have my database connection and display
Page1.xaml.cs:
public Page1()
{
InitializeComponent();
BindingContext = this;
var collection = firebaseClient
.Child("Childname")
.AsObservable<MyDatabaseRecord>()
.Subscribe((dbevent) =>
{
if (dbevent != null)
{
DatabaseItems.Add(dbevent.Object);
}
});
}
Page1.xaml:
<StackLayout Margin="15,0,15,5" BackgroundColor="Navy">
<CollectionView ItemsSource="{Binding DatabaseItems}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout>
<Frame BackgroundColor="Blue" HorizontalOptions="Center" Margin="0,0,0,17" Padding="2" WidthRequest="350" CornerRadius="20">
<StackLayout BackgroundColor="Blue">
<Label Text="{Binding Data1}" TextColor="White" FontAttributes="Bold" HorizontalOptions="Center" Margin="0, 5, 0, 0" FontSize="20"/>
<Label Text="{Binding Data2}" TextColor="White" Margin="10, 0, 0, 0" FontSize="15"/>
<Label Text="{Binding Data3}" TextColor="White" Margin="10, 0, 0, 0" FontSize="15"/>
<Label Text="{Binding Data4}" TextColor="White" Margin="10, 0, 0, 0" FontSize="15"/>
<Label Text="{Binding Data5}" TextColor="White" Margin="10, 0, 0, 20" FontSize="15"/>
</StackLayout>
</Frame>
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
How can I approach this?
Thanks in advance.
CodePudding user response:
There are two ways to solve this problem:
Using MessagingCenter: You can use
MessagingCenter.Send<MainPage>(this, "Hi");
to send.Then use below code to receive information:
MessagingCenter.Subscribe<MainPage> (this, "Hi", (sender) => { // Do something whenever the "Hi" message is received });
More information about MessagingCenter can be found here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center
You can pass the collection as a parameter when the two pages are jumped and then modify the bound collection.
For arrays of data you bind, it is recommended that you use ObservableCollection to dynamically update data.