Search code examples
c#asynchronousuwptextblock

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;    
   } 
} 

Solution

  • 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;
        });
    }