Search code examples
vb.netvisual-studiowindows-phone-7textblock

Change colour and size of a certain string in a textblock (Windows Phone 7) in VB.net


Hi I have a button (btnAdd) that adds the content of a textbox (txtName) to a textblock (lblName). I want to add a date to the textblock when btnAdd is pressed but I want it to be a different font size and colour. So far my code looks like

lblName.Text = txtName.Text " " + DateTime.Now

I only want DateTime.Now to be a different size and colour. Is this possible?

EDIT: Instead of a label I need to display it in a listBox my new code that I need help on is:

listBox1.Items.Add(txtName.Text " " + DateTime.Now)

Solution

  • What you want is to assign Inlines rather than Text:

    lblName.Inlines.Clear();
    lblName.Inlines.AddRange(new Inline[]
    {
        new Run(txtName.Text + " ")
        {
            Foreground = new SolidColorBrush(Color.Black)
        },
        new Run(DateTime.Now.ToString())
        {
            Foreground = new SolidColorBrush(Color.Green)
        }
    });
    

    You can (and should) also bind to Run's directly from XAML:

    <TextBlock>
        <TextBlock.Inlines>
            <Run Text="{Binding Name}" Foreground="Black" />
            <Run Text=" " Foreground="Black" />
            <Run Text="{Binding Now}" Foreground="Green" />
        </TextBlock.Inlines>
    </TextBlock>