在这种情况下如何设计MVVM
本文关键字:MVVM 这种情况下 | 更新日期: 2023-09-27 18:15:08
我有一个有三个视图的项目:
- ChartsView
- NewsView
- SettingsView
本质上,GraphsViewModel下载一些数据并将其表示为图表,NewsViewModel下载一些提要并将其表示为列表。两者都有一个定时器来决定下载数据的频率,所以还有一个与SettingsView相关联的SettingsViewModel,用户可以在其中决定这个设置和其他一些设置。
问题是:如何设置SettingsViewModel?
我做的第一件事是在setingsview中放入这样的东西:
<Pivot>
<PivotItem DataContext="{Binding Source={StaticResource Locator}, Path=GetNewsView}" Header="News Settings">
...
</PivotItem>
<PivotItem DataContext="{Binding Source={StaticResource Locator}, Path=GetChartView}" Header="Chart Settings">
...
</PivotItem>
</Pivot>
这是一个不好的做法吗?在某个地方,我读到要正确应用MVVM,我应该只使用每个视图的ViewModel。但在这种情况下,似乎(对我来说)错综复杂的设置到SettingsViewModel,并通过消息(MVVM光)发送到其他视图的值,他们需要。(在这种情况下,让两个主视图工作所需的设置被定义到它们中)
我想错了吗?
对于这种情况,有多少开发人员就有多少解决方案:)
我是这样做的:
我将创建一些对象来存储设置:
public class SettingsModel
{
public TimeSpan DownloadInterval {get; set;}
...
}
并在视图模型之间共享类的单例实例。这里我使用依赖注入来完成:
public class NewsViewModel
{
public NewsViewModel(SettingsModel settings)
{
//do whatever you need with the setting
var timer = new DispatcherTimer();
timer.Interval = settings.DownloadInterval;
//alternativly you can use something like SettingsModel.Current to access the instance
// or AppContext.Current.Settings
// or ServiceLocator.GetService<SettingsModel>()
}
}
public class SettingsViewModel
{
public SettingsViewModel(SettingsModel settings)
{
Model = settings;
}
public SettingsModel Model{get; private set;}
}