forked from Kinnara/ModernWpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadedVisualHost.cs
94 lines (78 loc) · 2.75 KB
/
ThreadedVisualHost.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Windows;
namespace ModernWpf.SampleApp.ThreadedUI
{
public class ThreadedVisualHost : ThreadedVisualHostBase
{
public ThreadedVisualHost()
{
DataContextChanged += OnDataContextChanged;
ThemeManager.AddActualThemeChangedHandler(this, OnActualThemeChanged);
}
#region ChildType
public static readonly DependencyProperty ChildTypeProperty =
DependencyProperty.Register(
nameof(ChildType),
typeof(Type),
typeof(ThreadedVisualHost),
new PropertyMetadata(OnChildTypeChanged));
public Type ChildType
{
get => (Type)GetValue(ChildTypeProperty);
set => SetValue(ChildTypeProperty, value);
}
private static void OnChildTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ctrl = (ThreadedVisualHost)d;
ctrl._childType = (Type)e.NewValue;
ctrl.InvalidateChild();
}
private Type _childType;
#endregion
public UIElement Child => ChildInternal;
protected override UIElement CreateChild()
{
UIElement child = null;
if (_childType != null)
{
child = Activator.CreateInstance(_childType) as UIElement;
if (child is FrameworkElement fe)
{
fe.DataContext = _dataContext;
}
}
return child;
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
_dataContext = e.NewValue;
if (ChildInternal is FrameworkElement fe)
{
fe.Dispatcher.Invoke(() => fe.DataContext = _dataContext);
}
}
private void OnActualThemeChanged(object sender, RoutedEventArgs e)
{
if (Child is FrameworkElement fe)
{
fe.Dispatcher.Invoke(() =>
{
// Invalidates all the properties on the nodes in the given sub-tree
var resources = fe.Resources;
if (resources.MergedDictionaries.Count == 0)
{
resources.MergedDictionaries.Clear();
}
else
{
var rd = new ResourceDictionary();
resources.MergedDictionaries.Add(rd);
rd.MergedDictionaries.Clear();
resources.MergedDictionaries.Remove(rd);
}
});
}
}
private object _dataContext;
}
}