Strange behavior of overridden TextBlock style

A few days ago, I came across strange behavior of the text inside Button (I assume that I would get the same behavior for other ContentControls). Let me explain the situation. I have a style definition in App.xaml for a 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 the style defined in App.xaml. Also I have 3 buttons in the window. The first button explicitly sets the contents of the TextBlock control inside. For the second button, I set the line as content in codebehind. For the third button, I set the integer value as the content in codebehind. Here is the MainWindow.xaml code:

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

Now what do we see? The text in the first and third buttons, as expected, has 0px fields, but the text in the second button has 10px fields! The question is why the second button has 10px fields and how to set zero fields for the second button (removing style from App.xaml is not possible)?

Thanks!

+4
source share
2 answers

When i change

 Button2.Content = "Button with string"; 

to

 Button2.Content = "Button with _string"; 

The button size changes from 10 to 0.

This is a bug in WPF; this has already been reported by Microsoft Connect .

I am not 100% sure, but I think that 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 due to the fact that the search for resources is performed by the logical tree, and not by the visual tree. The text blocks in buttons 2 and 3 are not inside the StackPanel logical tree.
+2
source

I can’t give you the final answer, but I notice that this is the difference between setting a string and an integer, which causes different styles to be applied.

Since setting the content to a value requiring a conversion leads to the correct style, I tried this:

 private void WindowLoaded(object sender, RoutedEventArgs e) { Button2.Content = new TextHolder("Button with string"); Button3.Content = 16; } public class TextHolder { private readonly string _text; public TextHolder(string text) { _text = text; } public override string ToString() { return _text; } } 

and the margin is now 0. I would be interested to understand what is happening.

0
source

All Articles