views:

2409

answers:

3

I have a databound TextBlock control (which is being used inside a DataTemplate to display items in a ListBox) and I want to make all the text in the control bold. I can't seem to find a property in the properties explorer to set the whole text to bold, and all I can find online is the use of the <Bold> tag inside the TextBlock, but I can't put that in as the data is coming directly from the data source.

There must be a way to do this - but how? I'm very inexperienced in WPF so I don't really know where to look.

A: 

You say that the data is coming directly from the datasource; is it possible to place a layer of abstraction in front of it? Its quite common to create a View for what you are displaying, and have the View communicate with the data. The most common implementation of this idea is Model View View-Model (MVVM). Have a read about it online.

You might have a 'DisplayText' property that is bound to the textbox, and it is simply a 'getter' that wraps the underlying text. It can detect if the text is already wrapped in and if not, wrap it.

Eg.

public class TestView {
  private Test datasource;
  public TestView(Test source)
  { 
     this.datasource = source;
  }

   public string DisplayText {
     get {
       if (datasource.Text.Contains("<bold>")==false) {
           return "<bold>" + datasource.Text + "</bold>";
       }
       return datasource.Text;
     }
   }
}

Then, bind to the View instead of directly to the object.

DarkwingDuck
A: 

Rather than just having a TextBlock, try this:

<TextBlock>
  <Bold>
    <Run />
  </Bold>
</TextBlock>

Then databind to the Run.TextProperty instead.

+10  A: 

Am I missing something, or do you just need to set the FontWeight property to "Bold"?

<TextBlock FontWeight="Bold" Text="{Binding Foo}" />
Matt Hamilton
Thanks! That works. However, the same thing doesn't work with a FontWeight of Italic. Is there a similarly easy way to do Italics?
robintw
Sure is! FontStyle. See http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.fontstyle.aspx
Matt Hamilton