Is there a way to change the color of a specific word/string at run time of a WPF ListBox Item?

484 views Asked by At

So all i want is if a specific word will be added in a listbox row/item, at run time, cause i am using a timer to add items at run time from my Database, i want that specific word/string to have a diferent color.

ie: All new item added that contains the string/word "Aproved", should be colored as green as soon as a new item its added to the WPF ListBox at run time.

 private void dispatcherTimerMensagem_Tick(object sender, EventArgs e)
    {
        if (!(principalDB.testarConexãoDB()))
        {
            dispatcherTimerVendasFechadas.Stop();
            dispatcherTimerMensagem.Stop();
            LstMensagem.ItemsSource = null;
            LbPbVendasFechadas.ItemsSource = null;
        }
        else
        {
            mensagem = principalDB.selectMessagemUsuario(null);

            if (mensagem != string.Empty)
            {
                this.Activate();
                LstMensagem.Opacity = 1;
                LstMensagem.Items.Add(principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem);

                voice.Voice = voice.GetVoices().Item(0);

                myWorkerMensagem.WorkerReportsProgress = true;
                myWorkerMensagem.WorkerSupportsCancellation = true;
                myWorkerMensagem.RunWorkerAsync();

                if (VisualTreeHelper.GetChildrenCount(LstMensagem) > 0)
                {
                    Border border = (Border)VisualTreeHelper.GetChild(LstMensagem, 0);
                    ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
                    scrollViewer.ScrollToBottom();
                }
            }
            else
            {
                LstMensagem.Opacity = 0.5;
            }
        }
    }

So the LstMensagem will recieve a new item at run time, from the variables declared, in this line of code:

 LstMensagem.Items.Add(principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem);

If a specific word/string comes up, as ie "aproved" i want that string with a different text color,as example, brushed in green.

1

There are 1 answers

5
dovid On BEST ANSWER

Use a TextBlock instead string. For entire item:

var text =  principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem;

var tb = new TextBlock();
tb.Text = text;

if(text.Contains("aproved"))
    tb.Foreground = Brushes.Green;

LstMensagem.Items.Add(tb);

For only part of the item, use the Inlines property to add different formatted texts:

var tb = new TextBlock();
tb.Inlines.Add(new Run { Foreground = Brushes.Green, Text = 
principalDB.mensagemRemetente});
tb.Inlines.Add(" (" + principalDB.mensagemData + ")" + ": " + mensagem);

LstMensagem.Items.Add(tb);