I am trying to learn how to call methods throughout a Wpf application.
In a basic experiment, I have two pages, PageData and MainPage.
PageData code:
namespace AppName
{
public sealed partial class PageData
{
public PageData()
{
this.InitializeComponent();
}
// works
private void Button_Click_1(object sender, RoutedEventArgs e)
{
mTest();
}
public bool mTest()
{
var newTbx = new TextBox{
Text = "Hello",
FontSize = 50
};
Grid.SetRow(newTbx, 3);
Grid.SetColumn(newTbx, 3);
gridMainPageData.Children.Add(newTbx);
return true;
}
}
}
MainPage code:
namespace AppName
{
public sealed class MainPage
{
public MainPage()
{
InitializeComponent();
}
private void pageRoot_Loaded(object sender, RoutedEventArgs e)
{
PageData passCall = new PageData();
mDisplayAlert(passCall.mTest().ToString());
}
}
}
It seems that the method mTest() completes because I get the “true” response when MainPage loads (I have a method mDisplayAlert that I use for showing messages on the MainPage UI), but the UI on PageData does not change. I know that mTest() works because the button click event on PageData does work.
Why does the UI not update when called from MainPage?
Because you create a new instance of
PageDatainsideMainPagewhen what you really want to do is use the same instance to access the exact same controls. When you call the.test()method you create a totally newTextBoxand assign data to a totally newGridwhen you think you are writing on you firstPageDatainstance.You have many options from there. You can :
PageDatainstance to you other form when you create it.PageDatainstance.StaticinPageDatato make sure the whole program share the same instance. (Not recommanded at all)Staticand create aStaticcopy of the control’s instance. Then the compiler will ask for a reference of aStaticcontrol and you can assign the instance copy usingControls.Find(yourControl).(Not a good practice either).Personally i’d use option number 1 but now you know you have the choice.