4

I've have a textblock and a textbox, I need to check and whether the textblock contains the textbox value, if yes then that specific value should be highlighted in some color. . .

For example,

TextBlock.Text="Just a Test"

if we type "te" in TextBox, then the value in the textblock should be highlight as "Just a *Te*st"

in xaml.

if anybody know means please say!

Thanks in Advance!

Gopinath Perumal
  • 2,258
  • 3
  • 28
  • 41
  • It is because I'm using the Microsoft.Phone.Userdata.contacts. my Question related to this is here http://stackoverflow.com/questions/14000521/how-to-highlight-the-result-from-context-sensitive-search-in-windows-phone-7 – Gopinath Perumal Dec 24 '12 at 13:47

2 Answers2

8

Hi i found the solution here's the underlying code that has been designed in MVVM pattern : EDIT : ** Pages -> MainPage.xaml.cs and ListViewModal has been changed according to ur need .

** was having some issue binding data from view modal so gave a quick response by doing it in code behind

MainPage.xaml

<phone:PhoneApplicationPage 
x:Class="FirstAppInCSharp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" Width="Auto" Height="Auto"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True" d:DesignHeight="768" d:DesignWidth="480">

<Grid Name='LayoutRoot'>
    <ListBox Height='500' Width='500' Background='Red'
        Name="ContactList"
        Margin="14,85,14,28" Loaded='ContactList_Loaded'
        Foreground="Black"
        ItemsSource='{Binding ListOftext}'
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel
                    Background='AliceBlue' Height='100' Width='500'
                    Orientation="Horizontal">
                    <TextBlock 
                        FontSize='30'
                        Height='70'
                        Foreground='Black'
                        Text='{Binding DisplayName}' Width='300'
                         />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

    <TextBox
        Height='72'
        HorizontalAlignment='Left'
        Margin='8,27,0,0'
        Name='textBox1'
        TextChanged='textBox1_TextChanged'
        VerticalAlignment='Top'
        Width='460' />
</Grid>

Now the MainPage.xaml.cs

public partial class MainPage : PhoneApplicationPage
{
    TextBlock textBlock1 = null;
    List<TextBlock> listText = null;
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        Contacts contact = new Contacts();
        contact.SearchAsync("", FilterKind.DisplayName, null);
        contact.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(contact_SearchCompleted);
    }
    void contact_SearchCompleted(object sender, ContactsSearchEventArgs e)
    {
        ContactList.DataContext = new ListViewModal(e.Results);
    }

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        SearchVisualTree(ContactList);

    }


    private void SearchVisualTree(DependencyObject targetElement)
    {

        var count = VisualTreeHelper.GetChildrenCount(targetElement);

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(targetElement, i);
            if (child is TextBlock)
            {
                textBlock1 = (TextBlock)child;
                HighlightText();
                break;
            }
            else
            {
                SearchVisualTree(child);
            }
        }
    }

    private void HighlightText()
    {
        if (textBlock1 != null)
        {
            string text = textBlock1.Text;
            textBlock1.Text = text;
            textBlock1.Inlines.Clear();

            int index = text.IndexOf(textBox1.Text);
            int lenth = textBox1.Text.Length;


            if (!(index < 0))
            {
                Run run = new Run() { Text = text.Substring(index, lenth), FontWeight = FontWeights.ExtraBold };
                run.Foreground = new SolidColorBrush(Colors.Orange);
                textBlock1.Inlines.Add(new Run() { Text = text.Substring(0, index), FontWeight = FontWeights.Normal });
                textBlock1.Inlines.Add(run);
                textBlock1.Inlines.Add(new Run() { Text = text.Substring(index + lenth), FontWeight = FontWeights.Normal });

                textBlock1.FontSize = 30;
                textBlock1.Foreground = new SolidColorBrush(Colors.Black);
            }
            else
            {
                textBlock1.Text = "No Match";
            }
        }

    }

    private void ContactList_Loaded(object sender, RoutedEventArgs e)
    {

    }
}

now the view modal for the list (I have added data manually)

public class ListViewModal : INotifyPropertyChanged
{
    public List<CheckList> ListOftext { get; set; }

    public ListViewModal(IEnumerable<Contact> iEnumerable)
    {
        ListOftext = new List<CheckList>();
        foreach (var list in iEnumerable) 
        {
            ListOftext.Add(new CheckList(){DisplayName = list.DisplayName});
        }
        RaisePropertyChanged("ListOftext");
    }



    /// <summary>
    /// Property changed method
    /// Executes when a property changes its value
    /// </summary>
    /// <param name="propertyName"></param>
    public void RaisePropertyChanged(string propertyName)
    {
        // this is the property changed method 
        //to detect property change
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private IEnumerable<Contact> iEnumerable;
}

now the data binding class (MOdel class)

public class CheckList
{
    public string DisplayName { get; set; }

}

thanks :) you can ask further questions if u want to or if you have any doubts .

Anobik
  • 4,841
  • 2
  • 17
  • 32
  • This will work for user defined list but I don't understand, How to populate the phone's contact list in the list view.... – Gopinath Perumal Dec 26 '12 at 05:30
  • Thanks For the Reply! Sorry to Disturb u. . . can u please say about the SearchVisualTree method. . . – Gopinath Perumal Dec 26 '12 at 08:25
  • Ur Code Works well but the list is populated once. . the list does not change according to the textchange .. . – Gopinath Perumal Dec 26 '12 at 08:50
  • 2
    VisualTreeHelper.GetChild(targetElement, i); this is the main part of code which searches for a child element. if u debug ur application u can identify how the thing iterates Visual tree is actually the alignment of elements as child and parents in a tree structure. we start the search from the parent node .. that is the contact list and check every branched element . If the element is not found then we move to the next branch. Hope this explanation helps . Did not include technicalities it will be easier for u to understand :) – Anobik Dec 26 '12 at 11:21
1

Heres a sample code to be put in the text box TextChange event

private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        string text = "this is a TextBlock";
        textBlock1.Text = text;
        textBlock1.Inlines.Clear();

        int index = text.IndexOf(textBox1.Text);
        int lenth = textBox1.Text.Length;


        if (!(index < 0))
        {
            Run run = new Run() { Text = text.Substring(index, lenth), FontWeight = FontWeights.ExtraBold };
            run.Foreground = new SolidColorBrush(Colors.Orange);
            textBlock1.Inlines.Add(new Run() { Text = text.Substring(0, index), FontWeight = FontWeights.Normal });
            textBlock1.Inlines.Add(run);
            textBlock1.Inlines.Add(new Run() { Text = text.Substring(index + lenth), FontWeight = FontWeights.Normal });

            textBlock1.FontSize = 30;
            textBlock1.Foreground = new SolidColorBrush(Colors.White);
        }
        else 
        {
            textBlock1.Text = "No Match";
        }
    }

this will highlight the text and return no match is no match is found.

note : this code snippet is case sensitive.

Anobik
  • 4,841
  • 2
  • 17
  • 32