【问题标题】:WPF 4 ContentPresenter TextWrapping style is not applied to implicitedly generated TextBlockWPF 4 ContentPresenter TextWrapping 样式不适用于隐式生成的 TextBlock
【发布时间】:2011-04-27 14:01:01
【问题描述】:

如果我将一段文本分配给ContentPresenterContent 属性,则TextBlock 控件会在渲染时由ContentPresenter 生成以包含该文本。

如果我创建一个适用于TextBlock 属性的样式并将其分配给该ContentPresenter,则它似乎不适用于隐式生成的TextBlocks。

<Style x:Key="SampleStyle">
  <Setter Property="TextBlock.TextWrapping" Value="Wrap"/>
</Style>

<ContentPresenter Content="This is a Test piece of text." Style="{StaticResource SampleStyle}"/>

有没有办法将此样式成功应用于自动生成的TextBlocks,而不是将其应用于所有TextBlocks(例如,将样式声明为TargetType="TextBlock"而没有Key)?

【问题讨论】:

    标签: wpf styles contentpresenter


    【解决方案1】:

    你可以这样做...

    <Window.Resources>
        <ResourceDictionary>
            <Style TargetType="{x:Type TextBlock}" x:Key="WrappingStyle">
                <Setter Property="TextWrapping" Value="Wrap"/>
            </Style>
        </ResourceDictionary>
    </Window.Resources>
    

    ...然后你定义你的ContentPresenter...

    <ContentPresenter Content="This text is going to wrap...">
                <ContentPresenter.Resources>
                    <Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource WrappingStyle}"/>
                </ContentPresenter.Resources>
    </ContentPresenter>
    

    TargetType 已设置,因为如您所知,ContentPresenter 并不总是包含TextBlock

    【讨论】:

      【解决方案2】:

      如果您没有在其他地方使用该样式,则可以将其直接应用于内容演示者:

      <ContentPresenter.Resources>
          <Style TargetType="{x:Type TextBlock}">
              <Setter Property="TextWrapping" Value="Wrap"/>
          </Style>
      </ContentPresenter.Resources>
      

      【讨论】:

      • 非常好的解决方案,这允许仅从字符串或字符串资源自动创建文本框的默认行为,自定义样式到文本框预定义,或者允许定义自定义内容,如果更多而不是一个简单的文本框是必需的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 1970-01-01
      相关资源
      最近更新 更多