WPF 4中的ContentPresenter TextWrapping样式未应用于隐式生成的TextBlock

14
如果我将文本赋值给ContentPresenterContent属性,那么在呈现时,ContentPresenter会生成一个TextBlock控件来包含该文本。
如果我创建一个应用于TextBlock属性的样式并将其分配给ContentPresenter,则似乎不适用于隐式生成的TextBlock
<Style x:Key="SampleStyle">
  <Setter Property="TextBlock.TextWrapping" Value="Wrap"/>
</Style>

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

除了将样式应用于所有TextBlock(例如将样式声明为没有KeyTargetType="TextBlock"),还有没有办法成功地将此样式应用于自动生成的TextBlock

2个回答

40

你可以这样做...

<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>

由于你知道 ContentPresenter 不总是包含一个 TextBlock,因此设置了 TargetType


10

如果你没有在其他地方使用这种样式,你可以直接将其应用于内容呈现器:

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

非常好的解决方案,它允许默认行为从字符串或字符串资源自动创建TextBox,并预定义了自定义样式到TextBox中,或者允许定义自定义内容,如果需要不止一个简单的TextBox。 - Alexander Gräf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接