Lucavin
Lucavin

Reputation: 41

How to know the fontsize is default or assiged value

do I have any way to know the fontsize of "Run" is assiged or defualt value? The code below could explain my purpose:

Run run = new Run();// here run.Fontsize is default maybe 12
run.FontSize = 12;// now it is assiged to 12
tbk.Inlines.Add(run);

tbk is a TextBlock defined in xaml, and its fontsize is set to 36. It's alway use the same fontsize with the TextBlock if Run's fontsize is a defualt value.

BTW, I must figure it out in a function, the object 'Run' is a parameter,and I konw nothing about it outside of the function.

Upvotes: 0

Views: 81

Answers (1)

grek40
grek40

Reputation: 13438

The following results in localValue2 = DependencyProperty.UnsetValue

object o1 = new Run("Test") { FontSize = 12 };
var r1 = o1 as TextElement;
if (r1 != null)
{
    // 12.0
    var localValue1 = r1.ReadLocalValue(TextElement.FontSizeProperty);
    // 12.0
    var getValue1 = r1.GetValue(TextElement.FontSizeProperty);
}
object o2 = new Run("Test");
var r2 = o2 as TextElement;
if (r2 != null)
{
    // UnsetValue
    var localValue2 = r2.ReadLocalValue(TextElement.FontSizeProperty);
    // 12.0
    var getValue2 = r2.GetValue(TextElement.FontSizeProperty);
}

However, when the TextElement is part of a tree, it might inherit non-default values from its parent. Then there is still no local value but its also not the default one.

object o3 = new Run("Test");
var textParent = new TextBlock(o3 as Run) { FontSize = 13 };
var r3 = o3 as TextElement;
if (r3 != null)
{
    // UnsetValue
    var localValue3 = r3.ReadLocalValue(TextElement.FontSizeProperty);
    // 13.0
    var getValue3 = r3.GetValue(TextElement.FontSizeProperty);
}

If you want to know the default value, use var runElementFontsizeDefault = TextElement.FontSizeProperty.GetMetadata(r1).DefaultValue; with a Run r1.

Open to debate: a parent element may have a different default value so if the local value is unset and the default value is different than the current value, you still don't know whether the parent value is default or modified (unless you check).

Upvotes: 1

Related Questions