TonicLoyal
TonicLoyal

Reputation: 103

write string to textblock on different page in C#, UWP

How can I write into a TextBlock on a different page?
So far it only works with TextBlocks on the same page.
The async function is in Page_1. The TextBlock is on Page_2.

public async void Serial() 
{
   string rxBuffer;
   //code
   //code
   //code

   while (true)
   {
      textblock_DebugRx_Gas_live.Text = rxBuffer;    
   } 
} 

Upvotes: 0

Views: 252

Answers (2)

Martin Zikmund
Martin Zikmund

Reputation: 39082

Usually, pages are displayed one at a time, so if you want to pass data between them during navigation, you should do so using the second parameter of the Frame.Navigate method:

this.Frame.Navigate(typeof(SecondPage), someString);

However, an even better solution is to use some kind of MVVM framework, which has a navigation service based on ViewModels, which have a longer lifetime than the UI controls/page. Frameworks like MvvvmCross, MvvmLight, SimpleMvvm or Reactive UI can all help you write such logic in an easier manner.

In your case, you could store the updated state in a view model, which would then be shared by both pages, so any change would be reflected in both places. Instead of directly writing into the Text property of the TextBlocks, you would implement a view model with a string property, which would trigger PropertyChanged event from the INotifyPropertyChanged interface. The MVVM pattern is well described in many tutorials so I encourage you to dig into it.

Upvotes: 2

Nico Zhu
Nico Zhu

Reputation: 32775

write string to textblock on different page in C#, UWP

If the two page display in foreground at same time like following.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>
    <StackPanel Margin="0,20,0,0" HorizontalAlignment="Center">
        <Button Click="Button_Click" Content="Click" />
        <TextBlock x:Name="Tbk" />
    </StackPanel>

    <Frame Grid.Row="1" VerticalAlignment="Center">
        <local:TestPage />
    </Frame>
</Grid>

You could use Messenger to send message from original page to target page.

using GalaSoft.MvvmLight.Messaging;

private void Button_Click(object sender, RoutedEventArgs e)
{
    var message = "Test";
    Messenger.Default.Send<string,TestPage>(message);
    Tbk.Text = message;
}

Target Page

public TestPage()
{
    this.InitializeComponent();
    this.Loaded += TestPage_Loaded;
}

private void TestPage_Loaded(object sender, RoutedEventArgs e)
{
    Messenger.Default.Register<string>(this, (s) =>
    {
        MyTextBlock.Text = s;
    });
} 

Upvotes: 2

Related Questions