dependency-propertiesdependencyobject

Set Padding only on elements that implement the Padding property


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


Solution

  • 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.