Chris Chris - 4 months ago 20
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"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfDemo"
StartupUri="View\FirstView.xaml">
<Application.Resources>

</Application.Resources>




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

StartupUri="View\SecondView.xaml"


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

<applicationSettings>
<WpfDemo.Properties.Settings>
<setting name="View" serializeAs="String">
<value>FirstView</value>
</setting>
</WpfDemo.Properties.Settings>
</applicationSettings>


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
view
variable at run time. For this task I do not want to use any MVVM frameworks.

Answer

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;
            base.OnStartup(e);
        }

Note

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