Issue
I have a Tabbedpage app that is supposed to send/pass "count" (number of clicks) variable in MianPage.xaml.cs to Page1.xaml. I need the label on Page1.xaml to show "count". Please let me your idea how I can fix it.
below is MainPage.xaml which is only a text and button :
<TabbedPage
xmlns:local="clr-namespace:bottomtest;assembly=bottomtest"
x:Class="buttontest.MainPage">
<ContentPage Title="MainPage" >
<StackLayout>
<Label Text="Welcome to MainPage1 !"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
<Button Text="Push Me" Clicked="Button_Clicked" />
</StackLayout>
</ContentPage>
<NavigationPage Title="Page1" >
<x:Arguments>
<local:Page1 />
</x:Arguments>
</NavigationPage>
</TabbedPage>
and MainPage.xaml.cs and where I want to send "count" are below:
namespace buttontest
{
public partial class MainPage : TabbedPage
{
public MainPage()
{
InitializeComponent();
}
int count = 0;
void Button_Clicked(object sender, System.EventArgs e)
{
count++;
((Button)sender).Text = $"You Pushed {count} times.";
// something here that send "count" to Page1.xaml
// like NI.Text = String.Format("${0:.##}", count);
}
}
}
Page1.xaml is just a Lable to show "count":
<ContentPage
x:Class="bottomtest.Page1"
Title="Page1">
<StackLayout>
<Label Text="PAGE 1 here"
FontSize="Large"/>
<Label Text="$0.0"
x:Name="NI"
HorizontalOptions="CenterAndExpand"></Label>
</StackLayout>
</ContentPage>
Page1.xaml.cs is below
namespace buttontest
{
public partial class Page1 : ContentPage
{
public Page1()
{
InitializeComponent();
}
}
}
Solution
You can use MessageCenter to achieve value transfer.
Here is the TabbedPage1 code:
public partial class TabbedPage1: TabbedPage
{
public TabbedPage1()
{
InitializeComponent();
}
public int count {get; set;}
private void Button_Clicked(object sender, EventArgs e)
{
count++;
((Button)sender).Text = $"You Pushed {count} times.";
MessagingCenter.Send<Object,int>(this, "Hi", count);
}
}
Here is the Page1 code:
public partial class Page1: ContentPage
{
public Page1()
{
InitializeComponent();
MessagingCenter.Subscribe<object, int>(this, "Hi", (sender, res) =>
{
NI.Text = Convert.ToString(res);
});
}
}
Here is a screenshot of the page:
Answered By - Wen xu Li - MSFT


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.