简体   繁体   中英

Set TextBlock to be entirely bold when DataBound in WPF

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.

我错过了什么,或者你只需​​要将FontWeight属性设置为“Bold”?

<TextBlock FontWeight="Bold" Text="{Binding Foo}" />

Rather than just having a TextBlock, try this:

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

Then databind to the Run.TextProperty instead.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM