2012-01-20 5 views
0

У меня есть реализация выделенного текста в datagrid, когда пользователь вводит текст в поле поиска и нажимает на поиск. Проблема заключается в , когда пользователь нажимает полосу прокрутки в datagrid, hightlight ушел. Ниже мой собственный класс для hightlighting:Выделить текст в Datagrid

public class SearchableTextBlock 
{ 
    public static DependencyProperty SearchPhraseProperty = 
     DependencyProperty.RegisterAttached(
      "SearchPhrase", 
      typeof(string), 
      typeof(SearchableTextBlock), new PropertyMetadata("", SearchPhraseChanged)); 

    public static string GetSearchPhrase(UIElement element) 
    { 
     return (string)element.GetValue(SearchPhraseProperty); 
    } 
    public static void SetSearchPhrase(UIElement element, string value) 
    { 
     element.SetValue(SearchPhraseProperty, value); 
    } 
    public static void SearchPhraseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     if (e.NewValue == null) 
      return; 

     if ((d as TextBlock) != null) 
     { 
      TextBlock tbx = d as TextBlock; 

      String text = tbx.Text; 
      tbx.Inlines.Clear(); 

      string txtStore = ""; 

      //Loops throught the entire text 
      for (int i = 0; i < text.Length; i++) 
      { 
       txtStore += text[i]; 
       //If search phrase is found 
       if (txtStore.ToUpper().IndexOf((e.NewValue as string).ToUpper()) > -1) 
       { 
        //Creates the formatting for regular text 
        Run runRegular = new Run(); 
        runRegular.Text = txtStore.Substring(0, txtStore.ToUpper().IndexOf((e.NewValue as string).ToUpper())); 

        //Creates the formatting for the found text 
        //Foreground is hardcoded to red. 
        Run runHighlight = new Run(); 
        runHighlight.Text = txtStore.Substring(txtStore.ToUpper().IndexOf((e.NewValue as string).ToUpper()), txtStore.Length - (txtStore.ToUpper().IndexOf((e.NewValue as string).ToUpper()))); 
        runHighlight.Foreground = new SolidColorBrush(Colors.Red); 
        runHighlight.FontWeight = FontWeights.Bold; 

        //Inserts the formatted text to the textblock 
        txtStore = ""; 
        tbx.Inlines.Add(runRegular); 
        tbx.Inlines.Add(runHighlight); 
       } 
      } 

      Run runRemaining = new Run(); 
      runRemaining.Text = txtStore; 
      tbx.Inlines.Add(runRemaining); 
     } 
    } 
} 

Вот мой XAML:

<sdk:DataGridTemplateColumn x:Name="Database" > 
       <sdk:DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <TextBlock Text="{Binding Database}" 
           sTextBlock:SearchableTextBlock.SearchPhrase="{Binding SDatabase, Mode=TwoWay}"/> 
        </DataTemplate> 
       </sdk:DataGridTemplateColumn.CellTemplate> 
      </sdk:DataGridTemplateColumn> 

Спасибо!

ответ

0

Вы можете попробовать отключить виртуализацию DataGrid. Попробуйте решение Xusan в this post.

Надеюсь, это поможет.

Miguel

Смежные вопросы