我正在尝试遵循 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/