views:

62

answers:

1

I am working with the classes in the System.Windows.Documents namespace, trying to write some generic code that will conditionally set the value of certain dependency properties, depending on whether these properties exist on a given class.

For example, the following method assigns an arbitrary value to the Padding property of the passed FrameworkContentElement:

void SetElementPadding(FrameworkContentElement element)
{
    element.SetValue(Block.PaddingProperty, new Thickness(155d));
}

However, not all concrete implementations of FrameworkContentElement have a Padding property (Paragraph does but Span does not) so I would expect the property assignment to succeed for types that implement this property and to be silently ignored for types that do not.

But it seems that the above property assignment succeeds for instances of all derivatives of FrameworkContentElement, regardless of whether they implement the Padding property. I make this assumption because I have always been able to read back the assigned value.

I assume there is some flaw in the way I am assigning property values. What should I do to ensure that a given dependency property assignment is ignored by classes that do not implement that property?

Many thanks for your advice.

Tim

+1  A: 

All classes that derive from Block have the Padding property. You may use the following modification:

void SetElementPadding(FrameworkContentElement element)
{
    var block = element as Block;
    if (block == null) return;

    block.Padding = new Thickness(155d);
}

Even without this modification everything would still work for you because all you want is for Padding to be ignored by classes that do not support it. This is exactly what would happen. The fact that you can read out the value of a Padding dependency property on an instance that does not support it is probably by design but you shouldn't care. Block and derivatives would honor the value and all others would ignore it.

wpfwannabe
Thanks for your answer. I was hoping to avoid type-specific code (like your test for whether the instance is a Block) as I have many methods to create, each of which may operate on any of the 23 types that derive from FrameworkContentElement. This is especially important for properties like BorderThickness, which is implemented independently in 4 different types. Nonetheless, your observation about unsupported properties being ignored is very helpful - it means that my methods can do the minimum, with the outcome being determined implicitly. Thanks again.
Tim Coulter
Another approach is to use Reflection and check explicitly if `Padding` or `BorderThickness` properties exist.
wpfwannabe