Created
May 8, 2018 23:45
-
-
Save toeb/67b1be206b269a9b883934d6cbc7cb35 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> A DependencyObject extension method that gets injection service by enumerating the visual tree. </summary> | |
/// | |
/// <remarks> Toeb, 2018-04-23. </remarks> | |
/// | |
/// <param name="TargetObject"> . </param> | |
/// | |
/// <returns> The injection service. </returns> | |
public static IInjectionService GetInjectionService(this DependencyObject TargetObject) | |
{ | |
// needs to be extended to look at the views themselves | |
foreach (var obj in TargetObject.EnumerateParentViewModels()) | |
{ | |
if (obj is IInjector ij) | |
{ | |
return ij.Injector; | |
} | |
} | |
return null; | |
} | |
/// <summary> Resolves the content for a specified dependency object. </summary> | |
/// | |
/// <remarks> Toeb, 2018-04-23. </remarks> | |
/// | |
/// <param name="TargetObject"> . </param> | |
/// <param name="content"> . </param> | |
/// <param name="parameters"> (Optional) </param> | |
/// | |
/// <returns> An object. </returns> | |
public static object ResolveContent(this DependencyObject TargetObject, object content, object[] parameters = null) | |
{ | |
var injectionService = TargetObject.GetInjectionService() ?? Application.Current.RootInjector(); | |
var reflectionService = injectionService?.GetService<IReflectionService>(); | |
if (content is string str) | |
{ | |
if (Regex.IsMatch(str, "^[a-zA-Z_][a-zA-Z_0-9]*$")) | |
{ | |
// identifier | |
if (injectionService != null) | |
{ | |
var types = reflectionService.FindTypeByPartialName(str).ToArray(); | |
var t = types.SingleOrDefault(); | |
if(t!=null) | |
{ | |
return injectionService.Construct(t, parameters); | |
} | |
} | |
} | |
try | |
{ | |
var componentUri = new Uri(BaseUriHelper.GetBaseUri(TargetObject), ".."); | |
if (Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out var newUri)) | |
{ | |
componentUri = newUri; | |
} | |
else | |
{ | |
componentUri = new Uri(componentUri, str); | |
} | |
var item = Application.LoadComponent(componentUri); | |
return item; | |
} | |
catch (Exception e) | |
{ | |
Trace.TraceInformation($"failed to load uri content {str}"); | |
return null; | |
} | |
} | |
if (content is Type type) | |
{ | |
if (injectionService == null) | |
{ | |
return null; | |
} | |
return injectionService.Construct(type, parameters); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment