Chris Chris - 1 year ago 104
C# Question

Using MVVM, how can I dynamically generate view by using App.config

I have application with two views in a separate xaml files (FirstView.xaml and SecondView.xaml). In the default mode the application generates the view from FirstView.xaml:

<Application x:Class="WpfDemo.App"


I can switch to the second view by editing the line:


This works fine on compile time but I would like to achieve this on run time. I created application settings with the following contents:

<setting name="View" serializeAs="String">

I can read the contents of the App.config file with:

string view = Properties.Settings.Default.View.ToString();

I would like to switch the view according to the
variable at run time. For this task I do not want to use any MVVM frameworks.

Answer Source

First step: Remove the StartupUri from your App.xaml.

Second Step: In the Code-Behind of your App.xaml do the following

protected override void OnStartup(StartupEventArgs e) {
            Uri dynamicUri = null;
            string view = Properties.Settings.Default.View.ToString();
            var result = Uri.TryCreate(view, UriKind.RelativeOrAbsolute, out dynamicUri);
            if (!result) throw new ApplicationException("Invalid settings found.");
            this.StartupUri = dynamicUri;


The question and the answer both have nothing to do with MVVM. For such a behavior, there is no MVVM solution, since everything has to happen before we get into DataBinding or else

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download