diff --git a/src/Uno.UI/UI/Xaml/Controls/AutoSuggestBox/AutoSuggestBox.cs b/src/Uno.UI/UI/Xaml/Controls/AutoSuggestBox/AutoSuggestBox.cs index 729ec22ac26a..a425ea012e9b 100644 --- a/src/Uno.UI/UI/Xaml/Controls/AutoSuggestBox/AutoSuggestBox.cs +++ b/src/Uno.UI/UI/Xaml/Controls/AutoSuggestBox/AutoSuggestBox.cs @@ -35,6 +35,7 @@ public partial class AutoSuggestBox : ItemsControl private string _userInput; private FrameworkElement _suggestionsContainer; private IDisposable _textChangedDisposable; + private IDisposable _textBoxLoadedDisposable; public AutoSuggestBox() : base() { @@ -52,7 +53,12 @@ protected override void OnApplyTemplate() _layoutRoot = GetTemplateChild("LayoutRoot") as Grid; _suggestionsList = GetTemplateChild("SuggestionsList") as ListView; _suggestionsContainer = GetTemplateChild("SuggestionsContainer") as FrameworkElement; - _queryButton = GetTemplateChild("QueryButton") as Button; + + // This is *expected* to be null on platforms with proper lifecycle. + // The queryButton is part of the TextBox template, which is not applied yet. + // On WinUI, QueryButton is never retrieved in OnTextBoxLoaded, not in OnApplyTemplate. + // We do in both to account for all our platforms. + _queryButton = _textBox?.GetTemplateChild("QueryButton") as Button; // Uno specific: If the user enabled the legacy behavior for popup light dismiss default // we force it to false explicitly to make sure the AutoSuggestBox works correctly. @@ -72,15 +78,25 @@ protected override void OnApplyTemplate() } #endif - UpdateQueryButton(); UpdateTextBox(); UpdateDescriptionVisibility(true); _textChangedDisposable?.Dispose(); + _textBoxLoadedDisposable?.Dispose(); if (_textBox is { }) { _textBox.TextChanged += OnTextBoxTextChanged; _textChangedDisposable = Disposable.Create(() => _textBox.TextChanged -= OnTextBoxTextChanged); + + if (_textBox.IsLoaded) + { + UpdateQueryButton(); + } + else + { + _textBox.Loaded += OnTextBoxLoaded; + _textBoxLoadedDisposable = Disposable.Create(() => _textBox.Loaded -= OnTextBoxLoaded); + } } Loaded += (s, e) => RegisterEvents(); @@ -103,6 +119,11 @@ private void OnTextBoxTextChanged(object sender, TextChangedEventArgs args) OnTextChanged(args.IsUserModifyingText); } + private void OnTextBoxLoaded(object sender, RoutedEventArgs args) + { + UpdateQueryButton(); + } + private void OnItemsChanged(IObservableVector sender, IVectorChangedEventArgs @event) { UpdateSuggestionList(); @@ -273,6 +294,7 @@ void RegisterEvents() if (_textBox != null) { _textBox.KeyDown += OnTextBoxKeyDown; + _queryButton = _textBox.GetTemplateChild