c# - 将连接字符串传递给 ViewModel 构造函数

标签 c# wpf xaml mvvm

我正在尝试遵循 MVVM 的最佳实践(据我了解)。我有一个解决方案,在我的主项目中使用 Views,在另一个项目中使用 ViewModels。我的主项目中有一个静态类,它根据命令行参数(例如/env=Production 或/env=Development)返回当前环境的连接字符串。

我想通过 XAML 将连接字符串注入(inject) ViewModel。以下工作,但它需要我在 XAML 中硬编码连接字符串:

<Window.DataContext>
    <ObjectDataProvider xmlns:sys="clr-namespace:System;assembly=mscorlib" ObjectType="vm:SchedulerViewModel">
        <ObjectDataProvider.ConstructorParameters>
            <sys:String>Data Source =.; Initial Catalog = MyDb_Dev; Integrated Security = true;</sys:String>
        </ObjectDataProvider.ConstructorParameters>
    </ObjectDataProvider>
</Window.DataContext>

有没有办法替换硬编码字符串 Data Source =.; Initial Catalog = MyDb_Dev; Integrated Security = true;调用我的静态类(名为 Global)中的公共(public)属性:Global.CnString ?还是我从根本上“做错了”?

最佳答案

这对我有用,但需要注意的是静态类 Global在 XAML 调用的命名空间中定义 local .

<ObjectDataProvider 
    ObjectType="vm:SchedulerViewModel"
    >
    <ObjectDataProvider.ConstructorParameters>
        <x:Static Member="local:Global.CnString" />
    </ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>

这个 viewmodel 构造函数被称为:
public SchedulerViewModel(string connString)
{
    ConnectionString = connString;
}

关于c# - 将连接字符串传递给 ViewModel 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46057142/

相关文章:

c# - .Net DownloadFileTaskAsync 健壮的 WPF 代码

c# - 使用 Visual C# 2008 Express 开发 Outlook 插件?

wpf - Prism with MVVM - 如何从外壳激活加载模块中的 View

wpf - 如何将 MenuItem.Header 绑定(bind)到 Window/UserControl 依赖属性?

c# - 如何根据我的鼠标旋转图片框

c# - 使用 x :Static 向 xaml 中的数组添加值

c# - 沿 XAML Shapes.Path 获取点

c# - C# 中的引用程序集使用什么 .NET 版本?

c# - 使用linq使用另一个条件删除一个列表中的元素

c# - 在 Visual Studio 中创建 WPF UI 的建议