Rene Sá
Rene Sá

Reputation: 4

Textbox, search without accents (ignore accents)

My Windows Phone app have a ListBox (populated from a JSON) and a TextBox used to search items on the ListBox.

This code works fine, but I need be able to search "lapis" and find "lápis". So, I need ignore accents on my search.

How do it?

        private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (Items != null)
        {
            this.List1.ItemsSource = Items.Where(w => w.descricao.ToUpper().Contains(SearchTextBox.Text.ToUpper()));
        }
    }

    private void WatermarkTB_GotFocus(object sender, RoutedEventArgs e)
    {
        if (SearchTextBox.Text == "Pesquisar Produto...")
        {
            SearchTextBox.Text = "";
            SolidColorBrush Brush1 = new SolidColorBrush();
            Brush1.Color = Colors.Red;
            SearchTextBox.Foreground = Brush1;
        }
    }

Upvotes: 2

Views: 345

Answers (2)

Extension method:

public static string RemoveDiacritic(this string text)
{
    return text.Normalize(NormalizationForm.FormD).Where(chara => CharUnicodeInfo.GetUnicodeCategory(chara) != UnicodeCategory.NonSpacingMark).Aggregate<char, string>(null, (current, character) => current + character);
}

Usage:

this.List1.ItemsSource = Items.Where(w => w.descricao.ToUpper().RemoveDiacritic().Contains(SearchTextBox.Text.ToUpper().RemoveDiacritic()));

Upvotes: 1

lisp
lisp

Reputation: 4198

Change

w.descricao.ToUpper().Contains(SearchTextBox.Text.ToUpper())

To

CultureInfo.CurrentCulture.CompareInfo.IndexOf(
    w.descricao, 
    SearchTextBox.Text, 
    CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) != -1

The meaning of IgnoreNonSpace

Indicates that the string comparison must ignore nonspacing combining characters, such as diacritics.

Upvotes: 3

Related Questions