Created
August 24, 2018 15:39
-
-
Save Kavignon/967d41b1ab6b6f51aa62cc7e89b9773b to your computer and use it in GitHub Desktop.
Sample content to try and load content of an attach property outside the UI thread
This file contains 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
// Class to be inside the WPF class | |
public static class CustomClass | |
{ | |
public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached( | |
"Text", | |
typeof(string), | |
typeof(CustomClass), | |
new UIPropertyMetadata(default(string))); | |
public static string GetText(DependencyObject obj) | |
{ | |
return (string)obj.GetValue(TextProperty); | |
} | |
public static void SetText(DependencyObject obj, string text) | |
{ | |
obj.SetValue(TextProperty, text); | |
} | |
} | |
// XAML file inside the WPF project | |
<Window | |
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" | |
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" | |
xmlns:system="clr-namespace:System;assembly=mscorlib" | |
x:Class="ComplexWpfApplication.TestingAttachedProperties" | |
Width="500" | |
Title="Atached Properties"> | |
<TextBlock CustomClass.Text="I should be able to read the text value"/> | |
</Window> | |
// Method use to load assembly up to reading the content of the Text property defined in the AttachProperty | |
var assembly = Assembly.LoadFrom(Path.Combine(assemblyLocation, "SomeAssembly" + ".dll")); | |
foreach(var uiElementType in assembly.assembly.GetTypes().Where(x => typeof(UIElement).IsAssignableFrom(x))) | |
{ | |
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; | |
ConstructorInfo[] constructors = typeToInstantiate.GetConstructors(bindingFlags); | |
// Some checks before instanciation | |
var uiElement = (UIElement)Activator.CreateInstance(typeToInstantiate, true); | |
foreach(var child in LogicalTreeHelper.GetChildren(uiElement)<UiElement>()) | |
{ | |
if(uiElemetInstance is TextBlock tBlock && !string.IsNullOrEmpty(CustomClass.GetText(tBlock)) | |
{ | |
//Great... I can read the attach property content | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment