WPF 4 ContentPresenter TextWrapping 样式不适用于隐式生成的 TextBlock [英] WPF 4 ContentPresenter TextWrapping style is not applied to implicitedly generated TextBlock

查看:29
本文介绍了WPF 4 ContentPresenter TextWrapping 样式不适用于隐式生成的 TextBlock的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I assign a piece of text to the Content property of a ContentPresenter, a TextBlock control is generated by the ContentPresenter at render time to contain that text.

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

If I create a style that applies toTextBlock properties and assign it to that ContentPresenter, the does not appear to apply to the implicitly generated TextBlocks.

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

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

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

Is there a way to apply this style successfully to the autogenerated TextBlocks short of applying it to all TextBlocks (e.g. declaring style as TargetType="TextBlock" with no Key)?

推荐答案

你可以这样做...

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

...然后在何处定义 ContentPresenter...

...then where you define your 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.

The TargetType is set since as you know the ContentPresenter will not always hold a TextBlock in it.

这篇关于WPF 4 ContentPresenter TextWrapping 样式不适用于隐式生成的 TextBlock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆