locked
How to specify key word's output format in TextBlock binding string? RRS feed

  • Question

  • For example: TextBlock binding a string and there are several key word: "PASS" in it, and I want to output the "PASS" as green color and bold font, how to do it?

    Thanks!

    Wednesday, August 22, 2012 6:41 AM

Answers

  • Hi OmegaMan,

    Thank you for your reminder and sorry for my delay reply.

    To highlight specific in Textblock, we need to first find the specific text's position(index) in TextBlock.

    Then to create a Textrange represent the specific text in textblock, and apply the background you want to the textrange. For detail code please refer to:

     public partial class MainWindow : Window
        {
            ObservableCollection<string> List1;
            ObservableCollection<string> List2;
            TextRange _txtrange = null;
            public MainWindow()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            }
            public DependencyObject FindChild(DependencyObject o, Type childType)
            {
                DependencyObject foundChild = null;
                if (o != null)
                {
                    int childrenCount = VisualTreeHelper.GetChildrenCount(o);
                    for (int i = 0; i < childrenCount; i++)
                    {
                        var child = VisualTreeHelper.GetChild(o, i);
                        if (child.GetType() != childType)
                        {
                            foundChild = FindChild(child, childType);
                        }
                        else
                        {
                            foundChild = child;
                            break;
                        }
                    }
                }
                return foundChild;
            }
            public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    string controlName = child.GetValue(Control.NameProperty) as string;
                    if (controlName == name)
                    {
                        return child as T;
                    }
                    else
                    {
                        T result = FindVisualChildByName<T>(child, name);
                        if (result != null)
                            return result;
                    }
                }
                return null;
            }
            void MainWindow_Loaded(object sender, RoutedEventArgs e)
            {
                List1 = new ObservableCollection<string>() 
                {
                    "aaa",
                    "bbb",
                    "ccc"
                };
                listBox1.ItemsSource = List1;
                List2 = new ObservableCollection<string>() 
                {
                    "bbbaaaaccca",
                    "bbbaaabaaccca",
                    "bbbaaaaaccca"
                };
                listBox2.ItemsSource = List2;
            }
            private void listBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                if (listBox1.SelectedItem != null)
                {
                    if (listBox2.SelectedItem != null)
                    {
                          var searchText = listBox1.SelectedItem.ToString();
                          ListBoxItem lbi = listBox2.ItemContainerGenerator.ContainerFromItem(listBox2.SelectedItem) as ListBoxItem;
                          var index = ((TextBlock)FindChild(((DependencyObject)lbi), typeof(TextBlock))).Text.IndexOf(searchText);
                                    if (index == -1)
                                    {
                                        return;
                                    }
                                    else
                                    {
                                        lbi = listBox2.ItemContainerGenerator.ContainerFromItem(listBox2.SelectedItem) as ListBoxItem;
                                        TextBlock txtblock = (TextBlock)FindChild(((DependencyObject)lbi), typeof(TextBlock));
                                        if (_txtrange != null)
                                        _txtrange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Transparent);
                                        _txtrange = new TextRange(txtblock.ContentStart, txtblock.ContentEnd);
                                        TextRange txtrangel = new TextRange(txtblock.ContentStart, txtblock.ContentStart.GetPositionAtOffset(index + 1));
                                        TextRange txtranger = new TextRange(txtblock.ContentStart.GetPositionAtOffset(index + 1 + searchText.Length), txtblock.ContentEnd);
                                        txtrangel.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
                                        txtranger.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
                                    }
                    }
                }
            }
        }
        <Window.Resources>
            <Style TargetType="ListBox">
                <Setter Property="ItemTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <StackPanel>                           
                                <Grid>                               
                                    <TextBlock x:Name="_textBlock" Text="{Binding}"></TextBlock>
                                </Grid>
                            </StackPanel>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Window.Resources>
        <Grid>
            <ListBox Height="100" HorizontalAlignment="Left" Margin="94,105,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" />
               
            <ListBox Height="100" HorizontalAlignment="Left" Margin="272,105,0,0" Name="listBox2" VerticalAlignment="Top" Width="120" SelectionChanged="listBox2_SelectionChanged" />
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="166,65,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" />
        </Grid>

    Hope it helps.

    Have a nice day.

    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by OmegaMan Wednesday, August 29, 2012 1:33 PM
    Wednesday, August 29, 2012 9:23 AM
  • Hi EricYi,

    Please check my sample about high light specific word that in different listbox for your reference:

    https://skydrive.live.com/?cid=0B578B4D6DED9B93&id=B578B4D6DED9B93%21106

    Hope it helps.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by Annabella Luo Wednesday, August 29, 2012 9:23 AM
    Thursday, August 23, 2012 10:02 AM

All replies

  • Hi EricYi,

    Please check my sample about high light specific word that in different listbox for your reference:

    https://skydrive.live.com/?cid=0B578B4D6DED9B93&id=B578B4D6DED9B93%21106

    Hope it helps.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by Annabella Luo Wednesday, August 29, 2012 9:23 AM
    Thursday, August 23, 2012 10:02 AM
  • Please check my sample about high light specific word that in different listbox for your reference:

    Hi Annabella,

    We all appreciate your work in creating a demo, but for future people who may be looking for a solution and have come across this post in a search, can you describe how the demo achieves result and possibly a code snippet? For there may come a time where you delete or remove access to the skydrive and this post becomes useless to any future readers.


    William Wegerson (www.OmegaCoder.Com)

    Thursday, August 23, 2012 12:55 PM
  • Hi OmegaMan,

    Thank you for your reminder and sorry for my delay reply.

    To highlight specific in Textblock, we need to first find the specific text's position(index) in TextBlock.

    Then to create a Textrange represent the specific text in textblock, and apply the background you want to the textrange. For detail code please refer to:

     public partial class MainWindow : Window
        {
            ObservableCollection<string> List1;
            ObservableCollection<string> List2;
            TextRange _txtrange = null;
            public MainWindow()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
            }
            public DependencyObject FindChild(DependencyObject o, Type childType)
            {
                DependencyObject foundChild = null;
                if (o != null)
                {
                    int childrenCount = VisualTreeHelper.GetChildrenCount(o);
                    for (int i = 0; i < childrenCount; i++)
                    {
                        var child = VisualTreeHelper.GetChild(o, i);
                        if (child.GetType() != childType)
                        {
                            foundChild = FindChild(child, childType);
                        }
                        else
                        {
                            foundChild = child;
                            break;
                        }
                    }
                }
                return foundChild;
            }
            public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i);
                    string controlName = child.GetValue(Control.NameProperty) as string;
                    if (controlName == name)
                    {
                        return child as T;
                    }
                    else
                    {
                        T result = FindVisualChildByName<T>(child, name);
                        if (result != null)
                            return result;
                    }
                }
                return null;
            }
            void MainWindow_Loaded(object sender, RoutedEventArgs e)
            {
                List1 = new ObservableCollection<string>() 
                {
                    "aaa",
                    "bbb",
                    "ccc"
                };
                listBox1.ItemsSource = List1;
                List2 = new ObservableCollection<string>() 
                {
                    "bbbaaaaccca",
                    "bbbaaabaaccca",
                    "bbbaaaaaccca"
                };
                listBox2.ItemsSource = List2;
            }
            private void listBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
            {
                if (listBox1.SelectedItem != null)
                {
                    if (listBox2.SelectedItem != null)
                    {
                          var searchText = listBox1.SelectedItem.ToString();
                          ListBoxItem lbi = listBox2.ItemContainerGenerator.ContainerFromItem(listBox2.SelectedItem) as ListBoxItem;
                          var index = ((TextBlock)FindChild(((DependencyObject)lbi), typeof(TextBlock))).Text.IndexOf(searchText);
                                    if (index == -1)
                                    {
                                        return;
                                    }
                                    else
                                    {
                                        lbi = listBox2.ItemContainerGenerator.ContainerFromItem(listBox2.SelectedItem) as ListBoxItem;
                                        TextBlock txtblock = (TextBlock)FindChild(((DependencyObject)lbi), typeof(TextBlock));
                                        if (_txtrange != null)
                                        _txtrange.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Transparent);
                                        _txtrange = new TextRange(txtblock.ContentStart, txtblock.ContentEnd);
                                        TextRange txtrangel = new TextRange(txtblock.ContentStart, txtblock.ContentStart.GetPositionAtOffset(index + 1));
                                        TextRange txtranger = new TextRange(txtblock.ContentStart.GetPositionAtOffset(index + 1 + searchText.Length), txtblock.ContentEnd);
                                        txtrangel.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
                                        txtranger.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Red);
                                    }
                    }
                }
            }
        }
        <Window.Resources>
            <Style TargetType="ListBox">
                <Setter Property="ItemTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <StackPanel>                           
                                <Grid>                               
                                    <TextBlock x:Name="_textBlock" Text="{Binding}"></TextBlock>
                                </Grid>
                            </StackPanel>
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Window.Resources>
        <Grid>
            <ListBox Height="100" HorizontalAlignment="Left" Margin="94,105,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" />
               
            <ListBox Height="100" HorizontalAlignment="Left" Margin="272,105,0,0" Name="listBox2" VerticalAlignment="Top" Width="120" SelectionChanged="listBox2_SelectionChanged" />
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="166,65,0,0" Name="textBlock1" Text="TextBlock" VerticalAlignment="Top" />
        </Grid>

    Hope it helps.

    Have a nice day.

    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

    • Marked as answer by OmegaMan Wednesday, August 29, 2012 1:33 PM
    Wednesday, August 29, 2012 9:23 AM