WPF 4 ContentPresenter TextWrapping 样式不适用于隐式生成的 TextBlock [英] WPF 4 ContentPresenter TextWrapping style is not applied to implicitedly generated TextBlock
问题描述
如果我将一段文本分配给 ContentPresenter
的 Content
属性,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
,则该样式似乎不适用于隐式生成的 TextBlock代码>s.
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 TextBlock
s.
<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 TextBlock
s short of applying it to all TextBlock
s (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屋!