【问题标题】:Programmatically change StartupUri以编程方式更改 StartupUri
【发布时间】:2018-09-09 17:51:11
【问题描述】:

我有两个窗口,取决于一个条件,我希望显示一个,否则我希望显示另一个窗口。

这是我迄今为止尝试过的。

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");
    }
}

但是,我不断收到两个不同的错误。

当我使用这条线时

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

我收到以下错误

当我使用这条线时

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

我收到以下错误

反正我能解决这个问题吗?

【问题讨论】:

    标签: c# wpf mvvm xamlparseexception application-start


    【解决方案1】:

    在@Jackdaw 的启发下,我想出了一个解决方案并意识到我的错误。

    我使用的是绝对路径,但 IDE 不喜欢它。然后我将路径更改为以下

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

    欢迎屏幕构造函数采用字符串参数,因此我创建了第二个不带参数的构造函数并使用了 Settings.Default.CurrentEmailAddress

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

    【讨论】:

    • 不应该是Resource File Pack URI,比如new Uri("pack://application:,,,/Views/UserSection/WelcomeScreen.XAML")吗?
    【解决方案2】:

    尝试为第二个 StartupUri 指定 UriKind.Relative 并使用如下相对路径:

    if (!string.IsNullOrEmpty(Settings.Default.CurrentEmailAddress) && !string.IsNullOrEmpty(Settings.Default.CurrentPassword))
    {
      StartupUri = new Uri(@"\FoodExpiry\FoodExpiry\Views\UserSection\WelcomeScreen.xaml", UriKind.Relative);
    }
    else
    {
      StartupUri = new Uri(@"\FoodExpiry\FoodExpiry\Views\RegisterViews\MainWindow.xaml", UriKind.Relative);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-10
      • 2015-08-16
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多