Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 17 additions & 20 deletions src/Plugin.Maui.KeyListener/KeyboardBehavior.Windows.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,38 +11,35 @@ namespace Plugin.Maui.KeyListener;

public partial class KeyboardBehavior : PlatformBehavior<VisualElement>
{
UIElement? _content;

protected override void OnAttachedTo(VisualElement bindable, FrameworkElement platformView)
{
base.OnAttachedTo(bindable, platformView);

var window = bindable.Window.Handler.PlatformView as Microsoft.UI.Xaml.Window;

window.Content.KeyDown += OnKeyDown;
window.Content.KeyUp += OnKeyUp;
window.Content.PreviewKeyDown += OnPreviewKeyDown;
window.Content.PreviewKeyUp += OnPreviewKeyUp;

//platformView.KeyDown += OnKeyDown;
//platformView.KeyUp += OnKeyUp;
//platformView.PreviewKeyDown += OnPreviewKeyDown;
//platformView.PreviewKeyUp += OnPreviewKeyUp;
if (bindable.Window?.Handler?.PlatformView is Microsoft.UI.Xaml.Window win && win.Content is UIElement content)
{
_content = content;
_content.KeyDown += OnKeyDown;
_content.KeyUp += OnKeyUp;
_content.PreviewKeyDown += OnPreviewKeyDown;
_content.PreviewKeyUp += OnPreviewKeyUp;
}
}

protected override void OnDetachedFrom(VisualElement bindable, FrameworkElement platformView)
{
base.OnDetachedFrom(bindable, platformView);

var window = bindable.Window.Handler.PlatformView as Microsoft.UI.Xaml.Window;

window.Content.KeyDown -= OnKeyDown;
window.Content.KeyUp -= OnKeyUp;
window.Content.PreviewKeyDown -= OnPreviewKeyDown;
window.Content.PreviewKeyUp -= OnPreviewKeyUp;
if (_content is null)
Copy link

Copilot AI May 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After unsubscribing the events in OnDetachedFrom, consider resetting _content = null; to release the reference and avoid holding onto the UI element longer than necessary.

Copilot uses AI. Check for mistakes.
return;

//platformView.KeyDown -= OnKeyDown;
//platformView.KeyUp -= OnKeyUp;
//platformView.PreviewKeyDown -= OnPreviewKeyDown;
//platformView.PreviewKeyUp -= OnPreviewKeyUp;
_content.KeyDown -= OnKeyDown;
_content.KeyUp -= OnKeyUp;
_content.PreviewKeyDown -= OnPreviewKeyDown;
_content.PreviewKeyUp -= OnPreviewKeyUp;
_content = null;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jeremy-visionaid why set content to null? I don't think this behavior should be responsible for that. What if the app is just removing the behavior but the content should remain unchanged?

}

void OnWindowKeyDown(object sender, Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e)
Expand Down
Loading