LennyL
LennyL

Reputation: 333

WinUI 3 Modify application's MainWindow Title from the Settings page in a NavigationView

I have a winui 3 desktop application running on Windows 10. In the setting page of the navigationview I want to allow the user to change environments and have the environment indicated in the MainWindow's Title.

On the MainWindow's code behind I initially set the title:

namespace MetricReporting
{
    /// <summary>
    /// An empty window that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.Title = $"EMB Metric Reporting Tool {getSelectedEnvironment()}";
            MasterContentFrame.Navigate(typeof(pageHome));
            MasterNavigation.Header = "Home";
            // Retrieve the window handle (HWND) of the current WinUI 3 window.
            var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
            // For EPPlus spreadsheet library for .NET         
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
        }

        private string getSelectedEnvironment()
        {
            return " (Non-Production)";
        }

In my button click method on my 'Settings' page, I do not know how to reference the MainWindow's Title:

private void envProd_Click(object sender, RoutedEventArgs e)
{
    DisplayEnvProddDialog();
    MainWindow.Title = $"EMB Metric Reporting Tool  (Production)";
}

The above code gets a syntax error of cs0120: An object reference is required for the non-static field, method, or property 'Window.Title'

Please help.
Thank you.

Upvotes: 0

Views: 349

Answers (1)

Andrew KeepCoding
Andrew KeepCoding

Reputation: 13213

You can make the MainWindow accessible:

App.xaml.cs

public partial class App : Application
{
    public App()
    {
        this.InitializeComponent();
    }

    public static MainWindow MainWindow { get; private set; }

    protected override void OnLaunched(LaunchActivatedEventArgs args)
    {
        MainWindow = new MainWindow();
        MainWindow.Activate();
    }
}

then in your SettingsPage:

private void Button_Click(object sender, RoutedEventArgs e)
{
    App.MainWindow.Title = "Your new title.";
}

Upvotes: 1

Related Questions