Skip to content

fix: UIElement Event Registration under NativeAOT - #22372

Merged
jonpryor merged 1 commit into
masterfrom
dev/jonpryor/jonp-rework-UIElement-event-registration-no-Reflection
Jan 21, 2026
Merged

jonpryor merged 1 commit into
masterfrom
dev/jonpryor/jonp-rework-UIElement-event-registration-no-Reflection

Conversation

@jonpryor

Copy link
Copy Markdown
Contributor

Context: 559b1f7
Context: https://github.com/unoplatform/uno-private/issues/1697#issuecomment-3752449412

(Repetition is fun!)

While running the uno.chefs app on macOS under NativeAOT:

dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop \
  -bl Chefs/Chefs.csproj -p:SelfContained=true -p:UseSkiaRendering=true\
  -p:PublishAot=true -p:IsAotCompatible=true \
  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true -p:IlcGenerateMetadataLog=true \
  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

while using Uno 6.5.0-dev.104 (and later), the Login page doesn't work properly. Specifically, after launching the app, click Skip to get to the Login page, and:

  • The Username field can be selected, but text cannot be entered.
  • The Password field cannot be selected via the mouse, but you can tab to it from the Password field.
  • You cannot enter text into the Password field.
  • You cannot check the [ ] Remember me checkbox.

You can click the Sign in with Apple and Sign in with Google buttons.

Why don't the <TextBox/> or <PasswordBox/> controls work?

Given that this is only under NativeAOT, the obvious answer is "Reflection!", but from where?

The less obvious answer is event registration, specifically the interaction between Control.SubscribeToPostKeyDown() and UIElement.GetIsEventOverrideImplemented(Type, string, Type[]):

partial class Control {
  [UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "Types manipulated here have been marked earlier")]
  private void SubscribeToPostKeyDown() {
    if (GetIsEventOverrideImplemented(GetType(), nameof(OnPostKeyDown), _keyArgsType))
      PostKeyDown += OnPostKeyDownHandler;
  }
}
partial class UIElement {
  private protected static bool GetIsEventOverrideImplemented(
    [DynamicallyAccessedMembers(…)] Type type, string name, Type[] args)
  {
    var method = type.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance, null, args, null);
    return method != null && method.IsVirtual
      && method.DeclaringType != typeof(UIElement)
      && method.DeclaringType != typeof(Control);
  }
}

In order for text input to work, the type must subscribe to the PostKeyDown event. In order for e.g. <TextBox/> to subscribe to the PostKeyDown event, it must override the OnPostKeyDown() method, and Control must determine that OnPostKeyDown() was overridden. This override check involves Reflection by way of Type.GetMethod(), which in turn requires that OnPostKeyDown be included in "reflection metadata."

It was not:

% grep OnPostKeyDown Chefs/obj/Release/net10.0-desktop/osx-x64/native/Chefs.metadata.csv
3432e2bf, ConstantStringValue, "OnPostKeyDown", ""

We need more than ConstantStringValue for it be useful. For example, if we add [DynamicDependency] to OnPostKeyDown():

partial class TextBox {
  [DynamicDependency(nameof(OnPostKeyDown))]
  private protected override void OnPostKeyDown(KeyRoutedEventArgs args) => …;
}

that fixes the "keyboard input doesn't work" problem, and Chefs.metadata.csv contains:

% grep OnPostKeyDown Chefs/obj/Release/net10.0-desktop/osx-x64/native/Chefs.metadata.csv
5009119c, Method, "[HasThis]  System.Void OnPostKeyDown(Microsoft.UI.Xaml.Input.KeyRoutedEventArgs)", "34117ead 56117ebb 6202258a 42117ec7"
34117ead, ConstantStringValue, "OnPostKeyDown", ""
42117ec7, CustomAttribute, "System.Diagnostics.CodeAnalysis.DynamicDependencyAttribute.[HasThis]  System.Void .ctor(System.String)(\"OnPostKeyDown\")(ctor: Internal.Metadata.NativeFormat.Handle", "6c0aa81f 34117ead"

However, this is not a scalable answer. Lots of codepaths touch GetIsEventOverrideImplemented(), notably
Control.EvaluateImplementedControlRoutedEvents(Type).

Do we really want (or need?) to add every Control method to reflection metadata?

It also doesn't fix the inabilty to interract with the checkbox.

Additionally, some parts of System.Reflection do not require "reflection metadata". In particular, it is possible to obtain MethodInfo instances without using Type.GetMethod(), by using delegates:

Action a = () => {};
MethodInfo method = a.Method;

This does not require "reflection metadata", and works under NativeAOT.

Rework Control.EvaluateImplementedControlRoutedEvents() et al to use delegates instead of Type.GetMethod():

partial class UIElement {
  private protected static bool GetIsEventOverrideImplemented<T>(Action<T> a) =>
    GetIsEventOverrideImplemented((Delegate)a);
  private protected static bool GetIsEventOverrideImplemented(Delegate d) =>
    d.Method.IsVirtual && d.Method.DeclaringType != typeof(UIElement) && d.Method.DeclaringType != typeof(Control);
}
partial class Control {
  private void SubscribeToPostKeyDown() {
    if (GetIsEventOverrideImplemented(OnPostKeyDown))
      PostKeyDown += OnPostKeyDownHandler;
  }
}

This works because delegates know about method overrides.

This not only works under NativeAOT, but also allows us to remove many [UnconditionalSuppressMessage] annotations.

However, in order for this to work, many methods which were previously static must now be instance methods, such as
Control.EvaluateImplementedControlRoutedEvents().

For backward compatibility/migration purposes, preserve the previous static methods and [Obsolete] them, directing code to use the instance method alternatives.

GitHub Issue: closes #

PR Type:

What is the current behavior? 🤔

What is the new behavior? 🚀

PR Checklist ✅

Please check if your PR fulfills the following requirements:

Other information ℹ️

@github-actions github-actions Bot added the platform/macos 🍏 Categorizes an issue or PR as relevant to the macOS platform label Jan 15, 2026
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@jonpryor
jonpryor force-pushed the dev/jonpryor/jonp-rework-UIElement-event-registration-no-Reflection branch from 542c661 to bc64bc2 Compare January 16, 2026 12:35
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 191541 has failed on Uno.UI - CI.

@jonpryor
jonpryor force-pushed the dev/jonpryor/jonp-rework-UIElement-event-registration-no-Reflection branch from bc64bc2 to 7340ba3 Compare January 20, 2026 02:52
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 192014 has failed on Uno.UI - CI.

Comment thread src/Uno.UI/UI/Xaml/UIElement.cs Resolved
Context: 559b1f7
Context: https://github.com/unoplatform/uno/issues/20533#issuecomment-3752449412

(Repetition is fun!)

While running the uno.chefs app on macOS under NativeAOT:

	dotnet publish -c Release -r osx-x64 -f net10.0-desktop -p:TargetFrameworkOverride=net10.0-desktop \
	  -bl Chefs/Chefs.csproj -p:SelfContained=true -p:UseSkiaRendering=true\
	  -p:PublishAot=true -p:IsAotCompatible=true \
	  -p:IlcGenerateMapFile=true -p:IlcGenerateMstatFile=true -p:IlcGenerateDgmlFile=true -p:IlcGenerateMetadataLog=true \
	  -p:EmitCompilerGeneratedFiles=true -p:CompilerGeneratedFilesOutputPath=`pwd`/_gen
	Chefs/bin/Release/net10.0-desktop/osx-x64/publish/Chefs

while using Uno 6.5.0-dev.104 (and later), the Login page doesn't
work properly.  Specifically, after launching the app, click **Skip**
to get to the Login page, and:

  * The `Username` field can be selected, but text cannot be entered.
  * The `Password` field cannot be selected via the mouse, but you
    can tab to it from the `Password` field.
  * You cannot enter text into the `Password` field.
  * You cannot check the `[ ] Remember me` checkbox.

You *can* click the **Sign in with Apple** and **Sign in with Google**
buttons.

Why don't the `<TextBox/>` or `<PasswordBox/>` controls work?

Given that this is only under NativeAOT, the obvious answer is
"Reflection!", but from where?

The less obvious answer is *event registration*, specifically the
interaction between `Control.SubscribeToPostKeyDown()` and
`UIElement.GetIsEventOverrideImplemented(Type, string, Type[])`:

	partial class Control {
	  [UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "Types manipulated here have been marked earlier")]
	  private void SubscribeToPostKeyDown() {
	    if (GetIsEventOverrideImplemented(GetType(), nameof(OnPostKeyDown), _keyArgsType))
	      PostKeyDown += OnPostKeyDownHandler;
	  }
	}
	partial class UIElement {
	  private protected static bool GetIsEventOverrideImplemented(
	    [DynamicallyAccessedMembers(…)] Type type, string name, Type[] args)
	  {
	    var method = type.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance, null, args, null);
	    return method != null && method.IsVirtual
	      && method.DeclaringType != typeof(UIElement)
	      && method.DeclaringType != typeof(Control);
	  }
	}

In order for text input to work, the type must subscribe to the
`PostKeyDown` event.  In order for e.g. `<TextBox/>` to subscribe to
the `PostKeyDown` event, it must override the `OnPostKeyDown()`
method, *and* `Control` must *determine* that `OnPostKeyDown()` was
overridden.  This override check involves Reflection by way of
`Type.GetMethod()`, which in turn requires that `OnPostKeyDown` be
included in "reflection metadata."

It was not:

	% grep OnPostKeyDown Chefs/obj/Release/net10.0-desktop/osx-x64/native/Chefs.metadata.csv
	3432e2bf, ConstantStringValue, "OnPostKeyDown", ""

We need *more* than `ConstantStringValue` for it be useful.
For example, if we add `[DynamicDependency]` to `OnPostKeyDown()`:

	partial class TextBox {
	  [DynamicDependency(nameof(OnPostKeyDown))]
	  private protected override void OnPostKeyDown(KeyRoutedEventArgs args) => …;
	}

that *fixes* the "keyboard input doesn't work" problem, and
`Chefs.metadata.csv` contains:

	% grep OnPostKeyDown Chefs/obj/Release/net10.0-desktop/osx-x64/native/Chefs.metadata.csv
	5009119c, Method, "[HasThis]  System.Void OnPostKeyDown(Microsoft.UI.Xaml.Input.KeyRoutedEventArgs)", "34117ead 56117ebb 6202258a 42117ec7"
	34117ead, ConstantStringValue, "OnPostKeyDown", ""
	42117ec7, CustomAttribute, "System.Diagnostics.CodeAnalysis.DynamicDependencyAttribute.[HasThis]  System.Void .ctor(System.String)(\"OnPostKeyDown\")(ctor: Internal.Metadata.NativeFormat.Handle", "6c0aa81f 34117ead"

However, this is not a scalable answer.  *Lots* of codepaths touch
`GetIsEventOverrideImplemented()`, notably
`Control.EvaluateImplementedControlRoutedEvents(Type)`.

Do we really want (or need?) to add every `Control` method to
reflection metadata?

Additionally, some parts of System.Reflection *do not require*
"reflection metadata".  In particular, it is possible to obtain
`MethodInfo` instances *without* using `Type.GetMethod()`,
by using *delegates*:

	Action a = () => {};
	MethodInfo method = a.Method;

This does not require "reflection metadata", and works under NativeAOT.

Rework `Control.EvaluateImplementedControlRoutedEvents()` et al to
use *delegates* instead of `Type.GetMethod()`:

	partial class UIElement {
	  private protected static bool GetIsEventOverrideImplemented<T>(Action<T> a) =>
	    GetIsEventOverrideImplemented((Delegate)a);
	  private protected static bool GetIsEventOverrideImplemented(Delegate d) =>
	    d.Method.IsVirtual
	      && method.DeclaringType != typeof(UIElement)
	      && method.DeclaringType != typeof(Control);
	}
	partial class Control {
	  private void SubscribeToPostKeyDown() {
	    if (GetIsEventOverrideImplemented(OnPostKeyDown))
	      PostKeyDown += OnPostKeyDownHandler;
	  }
	}

This works because delegates know about method overrides.

This not only works under NativeAOT, but also allows us to remove
several `[UnconditionalSuppressMessage]` annotations.

However, in order for this to work, many methods which were previously
`static` must now be instance methods, such as
`Control.EvaluateImplementedControlRoutedEvents()`.
@jonpryor
jonpryor force-pushed the dev/jonpryor/jonp-rework-UIElement-event-registration-no-Reflection branch from 7340ba3 to a89d366 Compare January 20, 2026 14:27
@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 192071 has failed on Uno.UI - CI.

@jonpryor jonpryor mentioned this pull request Jan 21, 2026
1 task done
@jonpryor
jonpryor enabled auto-merge January 21, 2026 12:29
@jonpryor
jonpryor merged commit d59b7fc into master Jan 21, 2026
53 checks passed
@jonpryor
jonpryor deleted the dev/jonpryor/jonp-rework-UIElement-event-registration-no-Reflection branch January 21, 2026 12:33
@jonpryor jonpryor mentioned this pull request Jan 22, 2026
1 task done
@github-actions github-actions Bot locked as resolved and limited conversation to collaborators May 2, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

platform/macos 🍏 Categorizes an issue or PR as relevant to the macOS platform

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants