fix(controls): TitleBar throws NRE when Collapsed#1671
fix(controls): TitleBar throws NRE when Collapsed#1671luca-domenichini wants to merge 2 commits intolepoco:mainfrom
Conversation
There was a problem hiding this comment.
Pull request overview
Fixes a crash in Wpf.Ui’s TitleBar Win32 message hook path when the control is Visibility=Collapsed (and therefore never templated), preventing repeated NullReferenceExceptions during mouse hover.
Changes:
- Adds a null-guard when iterating
_buttonsinsideHwndSourceHookto avoid dereferencing template parts beforeOnApplyTemplate()runs.
You can also share your feedback on Copilot code review. Take the survey.
| foreach (TitleBarButton button in _buttons) | ||
| { | ||
| if (!button.ReactToHwndHook(message, lParam, out IntPtr returnIntPtr)) | ||
| // Check if button is null to avoid potential NullReferenceException if OnApplyTemplate hasn't been called yet, e.g. when TitleBar has Visibility == Collapsed. | ||
| if (button == null || !button.ReactToHwndHook(message, lParam, out IntPtr returnIntPtr)) | ||
| { |
There was a problem hiding this comment.
_buttons is declared as TitleBarButton[] but is initialized with null elements until OnApplyTemplate() runs. Adding button == null here fixes the immediate NRE, but it leaves nullability inconsistent and still assumes _buttons contains no nulls in the inner loop (e.g., anotherButton.IsHovered). Consider making _buttons a TitleBarButton?[] (or using an _isTemplateApplied flag / Array.Empty<TitleBarButton>() until templated) and iterating only over non-null buttons to keep the hook logic robust and aligned with nullable reference types.
| // Check if button is null to avoid potential NullReferenceException if OnApplyTemplate hasn't been called yet, e.g. when TitleBar has Visibility == Collapsed. | ||
| if (button == null || !button.ReactToHwndHook(message, lParam, out IntPtr returnIntPtr)) | ||
| { |
There was a problem hiding this comment.
Please add a regression test for the reported scenario (TitleBar Visibility=Collapsed + mouse hover over the window) to ensure the window message hook no longer throws. There are existing FlaUI integration tests for TitleBar behavior, so this case should be covered to prevent reintroducing the NRE.
Pull request type
Please check the type of change your PR introduces:
What is the current behavior?
Issue Number: #1670
What is the new behavior?
Other information