Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Common Interface for FrameworkElement and FrameworkContentElement with dynamic programming

I try to cut it short: FrameworkElement and FrameworkContentElement share a lot of the same API but do not have a common Interface. Only DependencyObject as a base class.

I've come across this implementation of IFrameworkElement, which manually adds an interface and two wrapper classes. Now this code comes is implemented in .NET 3.5 and the author remarks that it would be a lot easier to do with dynamic programming in .NET 4:

The actual code is very simple, but about 624 lines long for each element. (It will be a much simpler one line implementation in a dynamic language - C# 4.0 is coming :) ).

I would be very curious how an implementation of that would look like. I assume it would boil down to a dynamic implementation of IFrameworkElement, and read about ExpandoObject and DynamicObject to see if I could implement myself, but I'm a bit stumped. I guess one can write a custom implementation of DynamicObject - but that isn't a one liner. Could this be really made that easy with dynamic programming? I doesn't even need to be a one liner, I'd be fine with 10 or even 100 lines instead of the original 1250.

I'm thinking something like this:

// Example, not working:
public IFrameworkElement AsFrameworkElement(FrameworkElement ele)
{
  dynamic ife = ele as IFrameworkElement;
  return ife;    
}

IFrameworkElement frameworkElement = AsFrameworkElement(new Button());
frameworkElement.DataContext = "Whatever";

IFrameworkElement frameworkContentElement = AsFrameworkElement(new Paragraph());
frameworkContentElement.DataContext = "Whatever again";
like image 702
Lennart Avatar asked Jun 25 '26 11:06

Lennart


1 Answers

Look at the original code of the blog:

var dataContect = "DataContext";
var frameworkElement = sender as FrameworkElement;
if ( frameworkElement != null )
{
    frameworkElement.DataContext = dataContect;
}
else
{
    var frameworkContentElement = sender as FrameworkContentElement;
    if ( frameworkContentElement != null )
    {
        frameworkContentElement.DataContext = dataContect;
    }
}

It would become

var dataContext = "DataContext"
dynamic element = sender;
element.DataContext = dataContext;

That's it already. At runtime, a property with the name DataContext will be searched for by reflection (be careful: when it comes to lists of dynamic types, things might slow down terribly), and then it is invoked.

Note: if the property does not exist, a RuntimeBinderException will be thrown. You might add some try...catch around the last line.

like image 194
Bernhard Hiller Avatar answered Jun 27 '26 23:06

Bernhard Hiller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!