1
public
class ViewModelManager
2 {
3
private
static Application app = Application.Current;
4
5
public
static
void InjectViewModelsToResources()
6 {
7
foreach (AssemblyPart ap
in Deployment.Current.Parts)
8 {
9
var sri = Application.GetResourceStream(
new Uri(ap.Source, UriKind.Relative));
10
var assembly =
new AssemblyPart().Load(sri.Stream);
11
12 InjectViewModelsToResources(assembly);
13
14 }
15 }
16
17
public
static
void InjectViewModelsToResources(Assembly assembly)
18 {
19
foreach (Type type
in assembly.GetTypes())
20 {
21
var attributes = type.GetCustomAttributes(
false);
22
23
foreach (
var attribute
in attributes)
24 {
25
if (attribute
is StaticResourceAttribute)
26 {
27
var resourceKey = ((StaticResourceAttribute)attribute).Key;
28
if (
string.IsNullOrEmpty(resourceKey))
29 resourceKey = type.Name;
30
31
var obj = Activator.CreateInstance(type);
32
if (!app.Resources.Contains(resourceKey))
33 app.Resources.Add(resourceKey, obj);
34 }
35 }
36 }
37 }
38
39
public
static T GetViewModelFromResources<T>()
40 {
41
var key =
typeof(T).Name;
42
if (app.Resources.Contains(key))
43
return (T)app.Resources[key];
44
else
45
return
default(T);
46 }
47 }