C# 在 WPF 中的 DataBound 时将 TextBlock 设置为完全粗体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/506521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:04:49  来源:igfitidea点击:

Set TextBlock to be entirely bold when DataBound in WPF

c#.netwpfxamltextblock

提问by robintw

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.

我有一个数据绑定 TextBlock 控件(在 DataTemplate 中使用它来显示 ListBox 中的项目),我想将控件中的所有文本设为粗体。我似乎无法在属性资源管理器中找到将整个文本设置为粗体的属性,而我在网上所能找到的只是<Bold>在 TextBlock 中使用了标记,但是随着数据的到来,我无法将其放入直接来自数据源。

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.

必须有一种方法可以做到这一点 - 但如何呢?我在 WPF 方面非常缺乏经验,所以我真的不知道去哪里找。

采纳答案by Matt Hamilton

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

我是否遗漏了什么,或者您是否只需要将 FontWeight 属性设置为“Bold”?

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

回答by DarkwingDuck

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.

你说数据直接来自数据源;是否可以在它前面放置一个抽象层?为您正在显示的内容创建一个视图,并让该视图与数据进行通信是很常见的。这个想法最常见的实现是模型视图视图模型(MVVM)。在线阅读有关它的信息。

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.

您可能有一个绑定到文本框的“DisplayText”属性,它只是一个包装底层文本的“getter”。它可以检测文本是否已经被换行,如果没有,就换行。

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.

然后,绑定到视图而不是直接绑定到对象。

回答by user60401

Rather than just having a TextBlock, try this:

而不是只有一个 TextBlock,试试这个:

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

Then databind to the Run.TextProperty instead.

然后将数据绑定到 Run.TextProperty。