The namespace System.Windows.Documentsincludes several classes with a Inlinestype property InlineCollection. For example, classes Paragraph, Boldand Hyperlinkhave this property.
Each of these classes is decorated ContentPropertyAttribute...
[ContentPropertyAttribute("Inlines")]
public class Paragraph : Block
... this means that it is easy enough, using reflection, to find that a given object provides this property.
However, I need to have access to this property in a strongly typed way by choosing the types that implement it.
I am a little surprised that Microsoft did not force all of these classes to implement the " IInlineContainer" interface , which would simplify type checking and casting.
However, in the absence of such an interface, is there any way to fake this polymorphic functionality, ideally, without clogging my code with a lot of conditions and type checking?
Thanks so much for your ideas,
Tim
Edit:
Thanks for your suggestions. A number of people have proposed the idea of a wrapper class, but this is not possible in my situation, since the targets were not created by my code, but by other classes in the .NET environment, for example, the Xaml parser or the RichTextBox control (in which the containing one is edited FlowDocument).
Edit 2:
There were some great suggestions here, and I thank everyone who shared their ideas. The solution I chose to implement uses the extension methods that were proposed by @qstarin, although I refined the concept to suit my needs as follows:
public static InlineCollection GetInlines(
this FrameworkContentElement element)
{
if (element == null) throw new ArgumentNullException("element");
if (element is Paragraph)
{
return ((Paragraph) element).Inlines;
}
else if (element is Span)
{
return ((Span)element).Inlines;
}
else
{
return null;
}
}
( , ), , , .