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

送分小仙女□ 提交于 2021-01-29 13:30:17

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/58175619/write-string-to-textblock-on-different-page-in-c-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!