0

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}" />
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298
  • try to find it with ancestor https://stackoverflow.com/questions/84278/how-do-i-use-wpf-bindings-with-relativesource or make sure your viewmodels share the text (property) somehow and bind each individually. – Sven Bardos Sep 22 '22 at 06:12
  • share the ViewModels can also work in UWP applications. Some introductions here https://learn.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth#binding-object-declared-using-binding – Junjie Zhu - MSFT Sep 22 '22 at 06:29

1 Answers1

0

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.

Simon Mourier
  • 132,049
  • 21
  • 248
  • 298