Restore dynamic resource value

北城以北 提交于 2021-02-05 09:26:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!