Search code examples
c#wpfstylestextblock

Strange behaviour of overridden Style of TextBlock


Some days ago I've faced with strange behaviour of text inside Button (I guess the same behaviour I would got for other ContentControls). Let me explain the situation. I have a style definition in App.xaml for TextBlock:

<Application.Resources>
    <Style TargetType="{x:Type TextBlock}">
        <Setter Property="Margin" Value="10"/>
    </Style>
</Application.Resources>

In MainWindow.xaml I have the same style definition, that should override style that defined in App.xaml. Also I have 3 buttons in Window. In first button explicitly defined TextBlock control inside button's content. For second button I set a string as content in codebehind. For third button I set an integer value as content in codebehind. Here is code of MainWindow.xaml:

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Margin" Value="0"/>
        </Style>
    </StackPanel.Resources>
    <Button Name="Button1">
        <Button.Content>
            <TextBlock Text="Button with text block"/>
        </Button.Content>
    </Button>
    <Button Name="Button2" />
    <Button Name="Button3" />
</StackPanel>

and MainWindow.xaml.cs:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    Button2.Content = "Button with string";
    Button3.Content = 16;
}

And now what we see? Text in first and third buttons, as expected, have margins 0px, but text in second button have margins 10px! The question is: why second button has 10px margins and how set zero margins for second button (removing style from App.xaml is not possible)?

Thank you!


Solution

  • When I change

    Button2.Content = "Button with string"; 
    

    to

    Button2.Content = "Button with _string"; 
    

    the button's margin changes from 10 to 0.

    This is a bug in WPF; it already has been reported on Microsoft Connect.

    I am not 100% sure but I think the behavior you saw is caused by the same root cause.

    By the way: the correct behavior would be that buttons 2 and 3 have Margin=10; this is because resource lookup is performed along the logical tree, not along the visual tree. The TextBlocks in the buttons 2 and 3 are not inside the logical tree of the StackPanel.