我正在为我的应用程序构建一个设置对话框,现在所有设置都与主视图模型上的设置相对应,但是当我添加更多视图和视图模型时,有些可能没有。
我需要知道将当前设置加载到设置对话框中的最佳做法是什么,然后如果用户单击“确定”,则将设置保存到相应的视图模型中。
我不会使用Properties.Settings.Default系统来存储设置,因为我希望我的应用程序尽可能便携,这会将用户范围设置存储在目录中:
C:\Users\ username \Local Settings\Application Data\ ApplicationName
而不是在我的应用程序目录中。
如果它有所不同,我使用的是Laurent Bugnion的MVVM Light Toolkit。
答案 0 :(得分:3)
如何使用工具包的Messenger实现它?
在设置ViewModel中进行更改时,您只需通知任何感兴趣的人:
Messenger.Send<Settings>(changedSettings);
所有需要知道设置是否已更改的View模型都会注册到该消息:
Messenger.Register<Settings>(this, delegate(Settings changedSettings){loadSettings(changedSettings);});
请在此处阅读:Mvvm light messenger或查看此类似帖子mvvm-light-how-to-access-property-in-other-view-model
答案 1 :(得分:1)
您可以使用MEF,从每个视图模型导出设置视图,并将它们导入为您添加到堆栈面板的视图列表,或者在主设置视图中将其导入。
使用MEF的一个很好的信息来源是:http://mef.codeplex.com/wikipage?title=Guide
这是一个我打算早点起床的示例程序:
使用System; 使用System.Collections.Generic; 使用System.ComponentModel.Composition; 使用System.ComponentModel.Composition.Hosting; 使用System.Reflection;
namespace zTestConsole
{
public interface ISimple
{
string Message { get; }
}
[Export("SimpleHello",typeof(ISimple))]
public class SimpleHello : ISimple
{
[Export("Message")]
public string Message
{
get { return "Silverlight rocks!"; }
}
}
[Export("SimpleBello",typeof(ISimple))]
public class SimpleBello : ISimple
{
[Export("Message")]
public string Message
{
get { return "C# rocks!"; }
}
}
public class SimpleMultiCat
{
[ImportMany("Message")]
public IEnumerable<string> Messages { get; set; }
}
public class SimpleCat
{
[Import("SimpleHello")]
public ISimple simple { get; set; }
}
class Program
{
private static CompositionContainer container;
static void Main(string[] args)
{
AggregateCatalog catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
SimpleMultiCat cats = new SimpleMultiCat();
SimpleCat cat = new SimpleCat();
Program.container = new CompositionContainer(catalog);
try
{
Program.container.ComposeParts(cats);
foreach (string message in cats.Messages)
{
Console.WriteLine(message);
}
}
catch (CompositionException ex)
{
Console.WriteLine(ex.ToString());
}
Console.WriteLine();
try
{
container.ComposeParts(cat);
Console.WriteLine(cat.simple.Message);
}
catch (CompositionException ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
答案 2 :(得分:1)
我也遇到过这个问题。我的解决方案是拥有类似ISettingsService Model的东西。将有2个实现。一个用于真实服务,另一个用于设计时和单元测试。
这里有一个例子: http://compiledexperience.com/blog/posts/Blendable-MVVM-Dependency-Injection-and-Unit-Testing