如何在MVVM中实现appSettings

时间:2016-11-07 11:34:34

标签: wpf mvvm f# app-config

我正试图摆脱在WPF项目中使用appSettings的警告。

的App.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  ...

  <appSettings>
    <add key="Language" value="English" />
    <add key="Department" value="Production" />
  </appSettings>
</configuration>

模型

open System.Configuration

type UserSettings = {
    Language    : string
    Department  : string
} with 
    static member Null =
        {
        Language    = "English"
        Department  = "Production"
        }
    static member Load() =
        let config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        {
        Language    = config.AppSettings.Settings.["Language"].Value
        Department  = config.AppSettings.Settings.["Department"].Value
        }
    member this.Save() =
        let config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
        config.AppSettings.Settings.["Language"].Value   <- this.Language
        config.AppSettings.Settings.["Department"].Value <- this.Department
        config.Save() 

视图模型

open FSharp.ViewModule

type SettingsViewModel() as self = 
    inherit ViewModelBase()    

    let settings    = UserSettings.Load()

    let department  = self.Factory.Backing(<@ self.Department @>, settings.Department)

    ...

查看

<Window 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ViewModels;assembly=mySolution"
    xmlns:fsxaml="http://github.com/fsprojects/FsXaml"
    Title="{Binding Department}" Height="300" Width="400">
    <Window.DataContext>
        <local:SettingsViewModel/>
    </Window.DataContext>

    ...

</Window>

视觉设计师标记了行<local:SettingsViewModel/>并发出警告:

  

对象引用未设置为引用的实例。

这似乎是由各个层(MVVM)的启动顺序引起的。

更改

let settings    = UserSettings.Load()

let settings    = UserSettings.Null

解决警告。

第二种方法

open FSharp.Configuration
type configSettings = AppSettings<"app.config">

这一行<local:SettingsViewModel/>给出错误(仍然构建):

  

错误1在配置的“appSettings”部分找不到名称语言   文件。 (C:\ Program Files(x86)\ Microsoft Visual Studio   12.0 \ Common7 \ IDE \ XDesProc.exe.Config)

有没有办法实现appSettings不会导致警告/错误?

修改

用于第二种方法的图层:

模型

open FSharp.Configuration
type UserSettings = AppSettings<"app.config">

视图模型

open FSharp.ViewModule

type SettingsViewModel() as self = 
    inherit ViewModelBase()    

    let department  = self.Factory.Backing(<@ self.Department @>, UserSettings.Department)

    ...

0 个答案:

没有答案