summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.WinRT/NativeEventWrapper.cs
blob: e28ca0eb472a5559723540fb7d88b06a6a919c4b (plain)
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
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;

#if WINDOWS_UWP
namespace Xamarin.Forms.Platform.UWP
#else
namespace Xamarin.Forms.Platform.WinRT
#endif
{
	class NativeEventWrapper : INotifyPropertyChanged
	{
		static string TargetProperty { get; set; }
		static readonly MethodInfo s_handlerinfo = typeof(NativeEventWrapper).GetRuntimeMethods().Single(mi => mi.Name == nameof(OnPropertyChanged) && mi.IsPublic == false);

		public NativeEventWrapper(object target, string targetProperty, string updateSourceEventName)
		{
			TargetProperty = targetProperty;
			try {
				var updateSourceEvent = target.GetType().GetRuntimeEvent(updateSourceEventName);
				MethodInfo addMethod = updateSourceEvent.AddMethod;
				MethodInfo removeMethod = updateSourceEvent.RemoveMethod;
				ParameterInfo[] addParameters = addMethod.GetParameters();
				Type delegateType = addParameters[0].ParameterType;
				var handlerDelegate = s_handlerinfo.CreateDelegate(delegateType, this);
				Func<object, EventRegistrationToken> add = a => (EventRegistrationToken)addMethod.Invoke(target, new object[] { handlerDelegate });
				Action<EventRegistrationToken> remove = t => removeMethod.Invoke(target, new object[] { t });
				WindowsRuntimeMarshal.AddEventHandler(add, remove, s_handlerinfo);
			}
			catch (Exception) {
				Log.Warning(nameof(NativeEventWrapper), "Can not attach NativeEventWrapper.");
			}
		}

		void OnPropertyChanged(object sender, RoutedEventArgs e)
		{
			PropertyChanged?.Invoke(sender, new PropertyChangedEventArgs(TargetProperty));
		}

		public event PropertyChangedEventHandler PropertyChanged;
	}
}