1

I have a program with MainWindow.xaml, MainWindow.xaml.cs, and Helper.cs files. All the UI is in the .xaml file and can only be accessed from the .xaml.cs file. But now I want to change the text in a TextBox in the MainWindow.xaml file from the Helper.cs file, which is completely separate.

I've tried creating a function in MainWindow.xaml.cs to do that:

public void SetRNrInfoText(string value)
{
    this.RNrInfoTextBox.Text = value;
}

or

public string RNrInfoText
{
    get { return this.RNrInfoTextBox.Text; }
    set { this.RNrInfoTextBox.Text = value; }
}

In Helper.cs file, I use:

public static void searchByRNR()
{
    MainWindow mainWindow = new MainWindow();
    mainWindow.SetRNrInfoText("new text"); 
}

However, when I try to call this searchByRNR function, nothing happens. In the .xaml file, "x:FieldModifier" is set to "public".

For now, the only idea I have is to make Helper return a dictionary or an array, and then in MainWindow, set all the values to certain textboxes, but I don't really like that idea.

So the question is, can I somehow change the property of a .xaml element in another .cs file, or is it not possible?"

Andrew KeepCoding
  • 7,040
  • 2
  • 14
  • 21
Rev1k
  • 37
  • 6
  • You didnt include the code where you call the searchByRNR function, this is the crucial part. you create a new instance of MainWindow thus nothing happens. – Aaron Feb 15 '23 at 09:11
  • Generally, you would do this with MVVM style. Have you considered a ViewModel class and use the [CommunityToolkit.Mvvm](https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/)? – Andrew KeepCoding Feb 15 '23 at 23:52

1 Answers1

1

MainWindow mainWindow = new MainWindow(); creates a new instance of the MainWindow class which is not what you want.

You need to get a reference to the already existing instance of the MainWindow in your Helper class somehow.

The easiest way to do this is probably to change the modifier of the m_window field in App.xaml.cs as suggested here.

You can then get a reference to the window in your Helper class like this:

public static void searchByRNR()
{
    MainWindow mainWindow = (Application.Current as App)?.m_window as MainWindow; 
    mainWindow.SetRNrInfoText("new text"); 
}
mm8
  • 163,881
  • 10
  • 57
  • 88