Skip to content

Fix: Add null check for AutoSuggestBox selection handling #3791

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 14, 2025
Merged

Fix: Add null check for AutoSuggestBox selection handling #3791

merged 1 commit into from
Feb 14, 2025

Conversation

hoaza
Copy link
Contributor

@hoaza hoaza commented Feb 11, 2025

This PR fixes the crash reported in #3741 where selecting an item from the AutoSuggestBox suggestions list causes a null reference exception.

Changes made:

  • Added defensive null checks in AutoSuggestionListBox_PreviewMouseDown
  • Improved selection handling logic to prevent null reference exceptions
  • Ensures safe handling of the SelectionChanged event

The fix prevents the crash by properly checking for null values before accessing SelectedItem and during the selection change process.

To test:

  1. Create an AutoSuggestBox with suggestions
  2. Type to show suggestions
  3. Select an item from the dropdown
  4. Verify no crash occurs and selection works as expected

Related issue: #3741

Refactored `AutoSuggestionListBox_PreviewMouseDown` in `AutoSuggestBox.cs` for improved readability and efficiency:
- Early return if `_autoSuggestBoxList` is `null` or `e.OriginalSource` is not a `FrameworkElement`.
- Defined `OnSelectionChanged` inline within its usage context.
- Streamlined logic by assigning and checking `selectedItem` immediately after initial checks.
- Set `e.Handled` to `true` earlier to mark the event as handled promptly.
- Simplified equality check using `Equals` method.
- Ensured `CommitValueSelection` is called appropriately for both newly selected and already selected items.
@Keboo Keboo added the release notes Items are likely to be highlighted in the release notes. label Feb 14, 2025
@Keboo Keboo added this to the 5.3.0 milestone Feb 14, 2025
@Keboo Keboo enabled auto-merge (squash) February 14, 2025 07:24
@Keboo Keboo merged commit 9289f6c into MaterialDesignInXAML:master Feb 14, 2025
2 checks passed
@hoaza hoaza deleted the fix/autosuggestbox-selection-null-check branch February 14, 2025 09:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
release notes Items are likely to be highlighted in the release notes.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants