【发布时间】:2012-03-21 09:10:58
【问题描述】:
我在玩 MVVM,了解模式中涉及的内容。我正在编写的第一个应用程序是一个非常小的应用程序,它基本上显示来自 App.Config 的 2 个设置。
我的目标是在单击按钮时能够写入此 app.config。
我的问题在于我不确切知道如何连接一个命令来委派这项工作,或者这是否是要走的路。
我的 App.config 非常简单:
<configuration>
<appSettings>
<add key="duration" value="100" />
<add key="operators" value="10" />
</appSettings>
</configuration>
模型如下:
get
{
// try to parse the setting from the configuration file
// if it fails return the default setting 0
int durationSetting = 0;
Int32.TryParse(ConfigurationManager.AppSettings["duration"], out durationSetting);
return durationSetting;
}
set
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("duration");
config.AppSettings.Settings.Add("duration", Convert.ToString(value));
ConfigurationManager.RefreshSection("appSettings");
config.Save();
}
}
那么,模型负责实际的数据访问,这就是我们想要的,对吧?
此外,我有一个 ViewModel(ViewModelBase 实现了 INotifyPropertyChanged):
public class SettingsViewModel : ViewModelBase
{
private Settings Settings { get; set; }
private SaveCommand saveCommand = new SaveCommand();
public ICommand SaveCommand
{
get
{
return saveCommand;
}
}
public SettingsViewModel(Settings settings)
{
if (settings == null)
throw new ArgumentNullException("Settings", "Settings cannot be null");
Settings = settings;
}
public int Duration
{
get { return Settings.Duration; }
set
{
if (Settings.Duration != value)
{
Settings.Duration = value;
RaisePropertyChanged("Duration");
}
}
}
视图是一个 xaml 用户控件,实例化如下:
public partial class MainWindow : Window
{
public SettingsViewModel SettingsViewModel { get; set; }
public MainWindow()
{
InitializeComponent();
DataContext = this;
Settings settings = new Settings();
SettingsViewModel = new SettingsViewModel(settings);
}
}
最后有一个实现 ICommand 的 SaveCommand,此时它基本上是空的。我已将命令连接到视图中的按钮。
但基本上,现在呢?处理保存值的最佳方法是什么? 我正在研究的示例是否过于做作?
【问题讨论】: