问题
I have a textblock tb with style.
<TextBlock x:Name="tb" Style="{DynamicResource H1Style}" Text="Test"/>
<Style TargetType="{x:Type TextBlock}" x:Key= "H1Style">
<Setter Property="FontSize" Value="18" />
<Setter Property="FontWeight" Value="Light"/>
</Style>
Then i change size
tb.FontSize = 5;
How do i restore style H1Style of tb?
I tried set SetResourceReference, but FontSize still 5 instead of 18.
tb.SetResourceReference(Control.StyleProperty, "H1Style");
回答1:
this line - tb.FontSize = 5;
- assigns local value to FontSize property of TextBlock. There is a way to undo assignment - ClearValue() method:
tb.ClearValue(TextBlock.FontSizeProperty);
FontSize is a dependency property and its value is computed according to DP value precedence
There are 3 sources from DP value precedence list:
local value
5
Style Setter value
18
default value of
FontSize
DP
ClearValue()
removes local value, causes recompute, and next value is provided by Style Setter which has highest priority from present sources
来源:https://stackoverflow.com/questions/62017881/restore-dynamic-resource-value