Reputation: 947
I have a TextBlock
inside a Border
, and I want to center align the TextBlock
by setting the property in the border's style:
<Border>
<Border.Resources>
<Style TargetType="Border">
<Setter Property="Background" Value="White"/>
<Setter Property="TextBlock.FontSize" Value="30"/>
<Setter Property="Width" Value="100"/>
<Setter Property="TextBlock.HorizontalAlignment" Value="Center"/>
<Setter Property="TextBlock.FontSize" Value="24" />
</Style>
</Border.Resources>
<TextBlock>123</TextBlock>
</Border>
But the textblock is not center aligned, while the other properties such as TextBlock.FontSize
is working properly. However, if I put the style in TextBlock
, or write another style inside the border style, it will work as expected.
<Border>
<Border.Resources>
<Style TargetType="Border">
<Setter Property="Background" Value="White"/>
<Setter Property="TextBlock.FontSize" Value="30"/>
<Setter Property="Width" Value="100"/>
<Setter Property="TextBlock.HorizontalAlignment" Value="Center"/>
</Style>
<Style.Resources>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center"/>
</Style>
</Style.Resources>
</Border.Resources>
<!-- or set the property here directly -->
<TextBlock HorizontalAlignment="Center">123</TextBlock>
</Border>
Why does this happen?
Upvotes: 0
Views: 82
Reputation: 128136
All properties in a Border Style are set on the Border element, not (directly) on any child element of the Border, regardless of the way you write the property name, and regardless whether the property setting makes sense on the target element. Setting a property that is not declared in the target type is possible due to the way dependency properties, or more precisely, attached properties work.
FontSize also affects the TextBlock, because the dependency property is registered in a way that its value is inherited by child elements. The FontSize property of the TextBox inherits its value from the FontSize property that is set on the Border.
See property value inheritance for details.
Upvotes: 1