Vua Gunny
Vua Gunny

Reputation: 1

WPF - How to replace part of text in AutoSuggestBox with selected word, instead of whole text?

In my wpf application I have created an AutoSuggestBox control:

<materialDesign:AutoSuggestBox x:Name="autoSuggestBox"
    materialDesign:TextFieldAssist.HasClearButton="True"
    Style="{StaticResource MaterialDesignFilledAutoSuggestBox}"
    Suggestions="{Binding keywordsdesc}"
    Text="{Binding AutoSuggestBox2Text, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
    TextChanged="AutoSuggestBox_TextChanged"
    SuggestionChosen="autoSuggestBox_SuggestionChosen" />

I want to replace only the last character string in the AutoSuggestBox with a selected suggestion word, this string is separated by any character in a list.

private ObservableCollection<string> keywordsdesc = new ObservableCollection<string>();
private static readonly char[] Separators = { ' ', '.', ',', ';', '(', ')', '[', ']', '{', '}', ' ', '\n', '\t' };

private void autoSuggestBox_TextChanged(object sender, TextChangedEventArgs e)
{
    string query = ExtractLastPart(autoSuggestBox.Text);
    if (!string.IsNullOrEmpty(query))
    {
        var suggestions = keywordsdesc.Where(k => k.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0).ToList();
        autoSuggestBox.Suggestions = suggestions;
    }
}
private string ExtractLastPart(string text)
{
    if (string.IsNullOrEmpty(text)) return string.Empty;
    var parts = text.Split(Separators, StringSplitOptions.RemoveEmptyEntries);

    return parts.LastOrDefault() ?? string.Empty;
}
private void autoSuggestBox_SuggestionChosen(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    e.Handled = true;

    var selectedItem = autoSuggestBox.SelectedValue as string;
    if (!string.IsNullOrEmpty(selectedItem))
    {
        string prefix = ExtractPrefix(autoSuggestBox.Text);
        autoSuggestBox.Text = $"{prefix}{selectedItem}";
        autoSuggestBox.CaretIndex = autoSuggestBox.Text.Length;
    }
}
private string ExtractPrefix(string text)
{
    if (string.IsNullOrEmpty(text)) return string.Empty;

    var parts = text.Split(Separators, StringSplitOptions.RemoveEmptyEntries);
    return string.Join(" ", parts.Take(parts.Length - 1));
}

I tried splitting the last string (separated by any character in Separators), and replacing only this string with the selected suggested word, but it always replaces the entire text in the AutoSuggestBox with the suggested word.

How should I handle this?

Upvotes: 0

Views: 25

Answers (0)

Related Questions