简体   繁体   中英

How to bind the Text property of a TextBlock from a different page

I've looked it up but have found no solutions to my seemingly unique situation. I am trying to figure out how I would be able to bind and set a TextBlock text from within a different page.

What I want to be able to do in ShellPage.xaml.cs

SomeValue = "Some text...";

Page2.xaml

<TextBlock Text="{Binding SomeValue}" Style="{ThemeResource SubtitleTextBlockStyle}" />

Make sure you add a Name and a FieldModifier attributes (from the http://schemas.microsoft.com/winfx/2006/xaml namespace, usually named "x") to the element you want to access, something like this:

<TextBlock
    x:Name="MyText"
    x:FieldModifier="public"
    Text="{Binding SomeValue}"
    Style="{ThemeResource SubtitleTextBlockStyle}"
/>

This will instruct the behind-the-scene-generator to generate a named item in your class and make it public in target language (here C#). This is an extract of the generated code:

partial class MainWindow : global::Microsoft.UI.Xaml.Window
{
    ...
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.UI.Xaml.Markup.Compiler", " 1.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    public void InitializeComponent()
    {
      ...
    }

    ...
    public global::Microsoft.UI.Xaml.Controls.TextBlock MyText;
    ...
   
}

Now, if you have an instance of MainWindow, you can call its members.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM