Search code examples
c#wpfmvvmxamlparseexceptionapplication-start

Programmatically change StartupUri


I have two windows and dependant upon a condition I want one to be displayed, otherwise I want the other window to be displayed.

this is what I have tried so far.

private void Application_Startup(object sender, StartupEventArgs e)
{
    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    if (!string.IsNullOrEmpty(Settings.Default.CurrentEmailAddress) && !string.IsNullOrEmpty(Settings.Default.CurrentPassword))
    {
        StartupUri = new Uri(@"C:\Users\User1\Desktop\FoodExpiryWC\FoodExpiry\FoodExpiry\Views\UserSection\WelcomeScreen.xaml", UriKind.Relative);
    }
    else
    {
        StartupUri = new Uri(@"C:\Users\User1\Desktop\FoodExpiryWC\FoodExpiry\FoodExpiry\Views\RegisterViews\MainWindow.xaml");
    }
}

However, I keep getting two different errors.

When I use the line

StartupUri = new Uri(@"C:\Users\User1\Desktop\FoodExpiryWC\FoodExpiry\FoodExpiry\Views\UserSection\WelcomeScreen.xaml", UriKind.Relative);

I get the following error

error version1

When i use the line

StartupUri = new Uri(@"C:\Users\User1\Desktop\FoodExpiryWC\FoodExpiry\FoodExpiry\Views\RegisterViews\MainWindow.xaml");

I get the following error

error version2

Is their anyway I can fix this?


Solution

  • With inspiration from @Jackdaw I have come up with a solution and realised my error.

    I was using the absolute path and the IDE didn't like it. I then changed the path to the following

    StartupUri = new Uri(@"./Views/UserSection/WelcomeScreen.xaml", UriKind.Relative);
    

    The welcome screen constructor took a string parameter so I created a second constructor with no parameter and used the Settings.Default.CurrentEmailAddress

    public WelcomeScreen()
            {
                InitializeComponent();
                this.DataContext = new WelcomeScreenViewModel(Settings.Default.CurrentEmailAddress);
            }