Is there any simple method to get CornerRadius from unknown UIElement?

Viewed 56

Like the header tells: Is the any simple method to get CornerRadius from unknown UIElement? Cannot use types FrameworkElement,UIElement,DependencyObject to check.

//Get the unknown FrameworkElement
object Target = Grid.Children[0];

CornerRadius TargetCorner;

//Check and get CornerRadius.... Any easier way to do this?
if (Target is Grid) TargetCorner = (Target as Grid).CornerRadius;
else if (Target is StackPanel) TargetCorner = (Target as StackPanel).CornerRadius;
else if (Target is RelativePanel) TargetCorner = (Target as RelativePanel).CornerRadius;
else if (Target is Border) TargetCorner = (Target as Border).CornerRadius;
else if (Target is Control) TargetCorner = (Target as Control).CornerRadius;

//ETC....
2 Answers

You can use the dynamic keyword instead of the object type:

//Get the unknown FrameworkElement
dynamic Target = Grid.Children[0];

CornerRadius cornerRadius;

try {
    cornerRadius = Target.CornerRadius;
} catch (RuntimeBinderException) {
    // No CornerRadius property
}

The dynamic keyword bypasses compile-time type checking and lets you try whatever operation you want at run-time, according to docs.microsoft.com:

The type is a static type, but an object of type dynamic bypasses static type checking. In most cases, it functions like it has type object. At compile time, an element that is typed as dynamic is assumed to support any operation.

You can use this behavior to test if a property exists on an object at run-time, and handle an exception if it doesn't.

Therefore, no compiler error is reported. However, the error does not escape notice indefinitely. It is caught at run time and causes a run-time exception.

You can try to verify if the class have a property with type CornerRadius, because if you look to documentation, CornerRadius is a struct. If you don't know how to this, look this post to have some ideia.

Related