Niewidzialny Niewidzialny - 1 year ago 67
C# Question

Is it good idea to create this same instance in one page class in UWP?

Sometimes when i wrote i had to eg edit a text in TextBlock which is on other Page, then I did this trick:

private static MainPage _gui;

public static void SetTitleText(string text) => _gui.TitleText.Text = text;

public static Visibility InfoCenterStackPanelVisibility
get { return _gui.InfoCenterStackPanel.Visibility; }
set { _gui.InfoCenterStackPanel.Visibility = value; }

public MainPage()

_gui = this;

And in other page i just call

And I want to know, is any other, better way to acces these items, without creating

ps I looked for any likely looking topics, I did not found an answer

Answer Source

Generally this is a bad idea because if your app gets complex enough you will end up in a situation where your MainPage doesn't exist at runtime, and thus will crash when you try and access the (null) static instance. This could happen eg if you implement Suspend / Terminate / Resume in a multi-page app, or you implement a contract like Share. Even if your current project is simple, this is a bad habit to get into if you build larger apps in the future.

Typically you would use an MVVM approach to have this information in your data model, and then the MainPage would just bind to the data model (or explicitly read values out of it). There are a lot of web resources for MVVM - just use your favourite search engine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download