Search code examples
c#wpf

WPF C# - Share Function across pages


So i have been banging my head around this problem for about 26 hrs now, and tried a lot of different situations and cant seem to find a solution.

MainWindow

        public async void StatusBox(string data)
        {
                await Task.Delay(500);
                blk_status.Text = data;
                await Task.Delay(3000);
                blk_status.Text = "";
        }

So im looking to call this function from another page so i can send test to that textbox.

Any Ideas? Thanks

Ive tried the Binding with the xaml and MVVM with no results.


Solution

  • You need to get a reference to the MainWindow instance from the page one way or another to begin with.

    The easiest way is probably to use the Application.Current.Windows property:

    var mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    if (mainWindow != null)
        mainWindow.StatusBox("...");
    

    If you use MVVM and bindings, you would typically bind to a command of a parent view model that executes the method. But there is nothing MVVM about your StatusBox method.