Search code examples
c#wpfxamlmethodsnon-static

How to call a method on MainWindows from another Page


I have MainWindow.xaml and another Page.xaml in same namespace

On MainWindow are textblock and frame.

Frame on MainWindow showing Page.xaml and on that Page is one Button.

I want Call non-static method in MainWindow with that Button, but i dont know how :(

For example:

MainWindow.xaml.cs

    namespace wpfapp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            openframe();
        }

        private void openframe()
        {
            frame1.Source = new Uri("testapge.xaml", UriKind.Relative);

        }
        public void MyMethod()
        {
            textblock1.Text = "This text is showed on MainWindow if i click to the Button";
        }    
    }
}

Page.xaml.cs

    namespace wpfapp
{
    public partial class Page : Page
    {
        public Page()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MainWindow trytocallit = new MainWindow();
            trytocallit.MyMethod();
        }
    }
}

This of course doesnt work. Thank for your help!


Solution

  • sorry for late reply, I have one simple resolution.

    • In Page.xaml create public string variable.
    • If you click to the button on the page, variable gets the some value.
    • Create new background theard on MainWindow and there runs an endless loop while (true) {..}
    • The cycle control of the value public string variable again and again... with Thread.Sleep(10);
    • If it finds a value that does something in MainWindow

    It works too and simply for me :)