C# 使用MVVM,如何使用App.config动态生成视图
我在一个单独的xaml文件(FirstView.xaml和SecondView.xaml)中有两个视图的应用程序。在默认模式下,应用程序从FirstView.xaml生成视图:C# 使用MVVM,如何使用App.config动态生成视图,c#,wpf,xaml,mvvm,C#,Wpf,Xaml,Mvvm,我在一个单独的xaml文件(FirstView.xaml和SecondView.xaml)中有两个视图的应用程序。在默认模式下,应用程序从FirstView.xaml生成视图: <Application x:Class="WpfDemo.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/w
<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>
这在编译时工作得很好,但我希望在运行时实现这一点。我使用以下内容创建了应用程序设置:
<applicationSettings>
<WpfDemo.Properties.Settings>
<setting name="View" serializeAs="String">
<value>FirstView</value>
</setting>
</WpfDemo.Properties.Settings>
</applicationSettings>
我想在运行时根据
view
变量切换视图。第一步:从App.xaml
中删除StartupUri
第二步:在App.xaml的代码隐藏中执行以下操作
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);
}
注意
问题和答案都与MVVM无关。对于这种行为,没有MVVM解决方案,因为在进入数据绑定之前,一切都必须发生,否则第一步:从你的
App.xaml
中删除StartupUri
第二步:在App.xaml的代码隐藏中执行以下操作
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);
}
注意
问题和答案都与MVVM无关。对于这种行为,没有MVVM解决方案,因为在我们进入数据绑定之前,一切都必须发生,否则为什么要这样做?我很好奇,因为我被自我毁灭的行为所吸引……你为什么要这么做?我很好奇,因为我被自我毁灭的行为所吸引。。。
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);
}