c# - 使用MVVM,如何使用App.config动态生成 View

标签 c# wpf xaml mvvm

我在单独的xaml文件(FirstView.xaml和SecondView.xaml)中具有两个 View 的应用程序。在默认模式下,应用程序从FirstView.xaml生成 View :

<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>

我可以通过编辑以下行切换到第二个 View :
StartupUri="View\SecondView.xaml"

这在编译时工作正常,但我想在运行时实现。我创建了具有以下内容的应用程序设置:
<applicationSettings>
    <WpfDemo.Properties.Settings>
        <setting name="View" serializeAs="String">
            <value>FirstView</value>
        </setting>
    </WpfDemo.Properties.Settings>
</applicationSettings>

我可以使用以下方法读取App.config文件的内容:
string view = Properties.Settings.Default.View.ToString();

我想在运行时根据view变量切换 View 。

最佳答案

第一步:从StartupUri中删除App.xaml

第二步:在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解决方案,因为所有事情都必须在进入DataBinding之前完成。

关于c# - 使用MVVM,如何使用App.config动态生成 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38805380/

相关文章:

WPF MenuItem 标题和 HeaderTemplate

c# - 使用 C# 和 .NET 进行审计

c# - 类似于 WinForms 控件中的 alt 标签

c# - ASP.Net MVC3 模型绑定(bind)错误

c# - 来自 BinaryFormatter.Deserialize 的 OutOfMemory 异常来自其内部 StringBuilder 调用

c# - 按钮命令未触发

c# - 是否可以在不同的网格后面有一个组件,在不同的网格上方有一个组件

wpf - 如何在 Expander Header 中设置多重绑定(bind)和图像

c# - 在 WPF 中,只有一个按钮的图标可以点击,而不是整个按钮

wpf - 如何更改每个DataGrid行详细信息的行详细信息数据模板中的TextBlock文本?