Interpolation no more

Mathematics isn’t my forte. That’s why each time I have to implement some form of interpolation, I feel a headache coming up. Even simple linear interpolation has been bugging me, as it’s the same thing over and over again. One of the beauties of software development is you can write something once, and as long as it works, you don’t have to worry about it anymore. Why then, have I already implemented interpolation for around 5 different data types? My latest need for interpolation, I finally decided to put some effort into this bugger and solve it once and for all.

Armed with a recently discovered library which allows usage of generics for calculations in C#, I managed to come up with the following classes.

Abstract interpolation class diagram.

Implementations of AbstractInterpolation decide on the type of interpolation between certain key points. How key points should be interpreted is decided by the implementation of AbstractKeyPointCollection. The difference between the two implementations will be demonstrated later. In order to know what to interpolate (the TValue template parameter), a trivial implementation of  AbstractTypeInterpolationProvider is required for the type which needs to be interpolated. All classes have a base class AbstractBasicArithmetic, which allows to do basic arithmetic operations on the specified template type TMath. This type determines the value type to use, and return for the calculations of the interpolation. They are done through a ‘Calculator‘ object, as specified in the generic calculations article. Normally you have to pass this calculator object yourself, but I created a CalculatorFactory which creates the corresponding correct calculator for known value types like double.

Perhaps, to better understand the design, a code sample is easier to demonstrate. Consider the desired result pictured in the following image. Of course to achieve drawing simple lines, better solutions exist, but for demonstration purposes, this works really well. The subsequent code sets up some points to interpolate between, and the interpolation which will be used.

CumulativeKeyPointCollection<Point, double> keyPoints = new
    CumulativeKeyPointCollection<Point, double>( new PointInterpolationProvider() );

keyPoints.Add( new Point( 50, 50 ) );
keyPoints.Add( new Point( 100, 100 ) );
...
keyPoints.Add( new Point( 300, 330 ) );

LinearInterpolation<Point, double> linear = new LinearInterpolation<Point, double>( keyPoints );

CumulativeKeyPointCollection is chosen instead of AbsoluteKeyPointCollection, because every key point added to the collection ‘continues’ on the previous point. The line needs to go through the points in the order in which they were added. When using AbsoluteKeyPointCollection, every key point has an absolute position. It doesn’t matter in which order the key points are added. E.g. Interpolating between known locations at specified times, where time is then used as the absolute position.

Next, some interpolated points are calculated as follows.

List<Point> interpolatedPoints = new List<Point>();
double curPercentage = 0;
while ( curPercentage < 1 )
{
    interpolatedPoints.Add( linear.Interpolate( curPercentage ) );
    curPercentage += 0.001;
}

And that’s how easy interpolation can be! To achieve the result as pictured earlier, I just draw line segments between all the calculated points, and draw rectangles on top of the key points. All that remains for the code to work, is the type provider for Point which was passed to the key point collection. As you can see, that’s just a simple implementation of AbstractTypeInterpolationProvider.

    /// <summary>
    ///   Allows AbstractInterpolation to interpolate over a list of points.
    /// </summary>
    public class PointInterpolationProvider : AbstractTypeInterpolationProvider<Point, double>
    {
        /// <summary>
        ///   Create a new provider to allow AbstractInterpolation to interpolate
        ///   between a list of points.
        /// </summary>
        public PointInterpolationProvider()
            : base( 2 )  // The amount of dimensions this type has.
        {
        }

        protected override double GetDimensionValue( Point value, int dimension )
        {
            switch ( dimension )
            {
                case 0:
                    return value.X;
                case 1:
                    return value.Y;
                default:
                    throw new NotSupportedException(
                        "Unsupported dimension while doing interpolation on type " +
                        typeof(Point) + "." );
            }
        }

        public override double RelativePosition( Point from, Point to )
        {
            // Pythagoras to get distance.
            return Math.Sqrt( Math.Pow( to.X - from.X, 2 ) + Math.Pow( to.Y + from.Y, 2 ) );
        }

        public override Point CreateInstance( double[] interpolated )
        {
            return new Point( interpolated[ 0 ], interpolated[ 1 ] );
        }
    }

To show the flexibility of this approach, cardinal spline interpolation is possible by just changing the used LinearInterpolation class to CardinalSplineInterpolation.

CardinalSplineInterpolation spline =
    new CardinalSplineInterpolation( keyPoints );

Every time I need to implement something a bit more mathematically challenging, and search for help, I seem to end up on web pages created during the Middle Ages of the internet. Aren’t there any reuseable libraries out there which support e.g. interpolation out of the box on the actual types you want to perform it on? Like Point in the before given sample. I experience that so many libraries implement concrete implementations instead of generic solutions. For the interpolation to work I had to implement a generic binary search algorithm because SortedList (used to store the key points) didn’t support a binary search out of the box. To indicate intervals of values I had to create a generic Interval class, which I immediately could use in other source files as well. All this, of course brings some overhead with it. Instead of Donald Knuth‘s famous “premature optimization is the root of all evil” quote, I find Bill Harlan’s succinct expression even better.

It is easier to optimize correct code than to correct optimized code. – Bill Harlan

Source code can be found as part of my FCL Extension library in the Whathecode.System assembly and namespace Whathecode.System.Arithmetic.Interpolation.

ViewModel Property and Command Factory

If you are familiar with the MVVM pattern, often used in WPF/XAML, you probably know what a viewmodel should look like. These classes get quite big pretty quickly. Considering that they are mainly just an adapter on your model, to be accessed by your view, they contain a lot of duplicate code. Wherever you read “duplicate”, there most likely exists a cleaner solution, so I’ll cut to the chase. What follows are two code samples with the same behavior. In the second sample I use a factory to minimize the required code. This approach has additional advantages as well as I’ll explain later.

Let’s make a ViewModel to edit this rubber duck! (This might sound familiar to you if you have read Head First’s great book on design patterns.)

Traditional implementation:

public class DuckViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Duck m_duck;

    private bool m_canQuack;
    public bool CanQuack
    {
        get { return m_canQuack; }
        set
        {
            m_canQuack = value;
            RaisePropertyChanged("CanQuack");
        }
    }

    private Color m_color;
    public Color Color
    {
        get { return m_color; }
        set
        {
            m_color = value;
            RaisePropertyChanged("Color");
        }
    }

    private RelayCommand m_quackCommand;
    public ICommand QuackCommand
    {
        get { return m_quackCommand; }
    }

    private RelayCommand m_saveCommand;
    public ICommand SaveCommand
    {
        get { return m_saveCommand; }
    }

    public DuckViewModel(Duck duck)
    {
        m_duck = duck;
        CanQuack = duck.CanQuack;
        Color = duck.Color;

        m_quackCommand = new RelayCommand(() => Quack(), () => CanQuack());
        m_saveCommand = new RelayCommand(() => Save());
    }

    public void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyEventArgs(property));
        }
    }

    public void Quack()
    {
        m_duck.Quack();
    }

    public void CanQuack()
    {
        return m_duck.CanQuack;
    }

    public void Save()
    {
        m_duck.CanQuack = CanQuack;
        m_duck.Color = Color;
    }
}

Phew, that’s a whole lot to write just for two properties and two commands isn’t it? Let’s try improving this.

Factory approach:

public enum Properties { CanQuack, Color }
public enum Commands { Save, Quack }

public class DuckViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private readonly NotifyPropertyFactory<Properties> m_properties;
    private readonly CommandFactory<Commands> m_commands;

    private Duck m_duck;

    [NotifyProperty(Properties.CanQuack)]
    public bool CanQuack
    {
        get { return (bool)m_properties.GetValue(Properties.CanQuack); }
        set { m_properties.SetValue(Properties.CanQuack, value); }
    }

    [NotifyProperty(Properties.Color)]
    public Color Color
    {
        get { return m_properties.GetValue(Properties.Color) as Color; }
        set { m_properties.SetValue(Properties.Color, value); }
    }

    public DuckViewModel(Duck duck)
    {
        m_duck = duck;
        CanQuack = duck.CanQuack;
        Color = duck.Color;

        m_properties = new NotifyPropertyFactory<Properties>(this, PropertyChanged);
        m_commands = new CommandFactory<Commands>(this);
    }

    [CommandExecute(Commands.Quack)]
    public void Quack()
    {
        m_duck.Quack();
    }

    [CommandCanExecute(Commands.Quack)]
    public bool CanQuack()
    {
        return m_duck.CanQuack;
    }

    [CommandExecute(Commands.Save)]
    public void Save()
    {
        m_duck.CanQuack = CanQuack;
        m_duck.Color = Color;
    }
}

There already exist dozens of other solutions to simplify (and improve) implementing INotifyPropertyChanged. One approach is to use a base class. I prefer the factory approach, following the design principle.

Favor composition over inheritance.

To remove the literals from the PropertyChanged call lambda’s can be used. Because my approach uses reflection, the literal isn’t a problem anymore, and is traded for an enum value.

Besides solving the previously mentioned problems, the factory approach has additional advantages:

  • No more private field members required for the properties, just one for the factory.
  • As an advantage of the factory design, the view model doesn’t need to know about concrete implementations. Behavior can be added/changed inside the factory.
  • As you might have noticed, no more command members! All the commands are contained within the command factory. Yes, you can still magically bind to them, which I’ll explain in a bit!

How it works:

You might notice the similarity with my previously posted dependency property factory. I refactored the latter, and all three factories (commands, notify property and dependency property) use the same abstract base class AbstractEnumSpecifiedFactory, which already handles a lot of the required behavior by using reflection. It links MemberInfo objects to the desired attributes. Concrete implementation decide which attributes it needs, and what to do with them.

To be able to still bind to the commands I created a custom Markup Extension for XAML, allowing me to do the following.

<Button Command="{m:CommandBinding {x:Static Binding:Commands.Quack}}" Content="Quack" />

This has another additional advantage that binding is done in a safe way. The CommandBinding extension uses -you guessed it- reflection to get the correct command out of the CommandFactory in the data context.

While creating the CommandBinding extension I prepared myself to optionally create a custom general Binding extension, so that the naming conventions for dependency properties can safely be ignored, and the useless property fields can be removed.

Source code can be found in my FCL Extension library in the Whathecode.PresentationFramework assembly. The NotifyPropertyFactory is located in Whathecode.System.ComponentModel.NotifyPropertyFactory and the CommandFactory is located in Whathecode.System.Windows.Input.CommandFactory.

Dependency Property Factory – Part 3

This post is a second follow-up to an earlier attempt to simplify creating dependency properties. In the previous follow-up I discussed unanswered questions about the WPF dependency property system which prevented me from continuing the implementation.

First of all, I would like to thank Einar Ingebrigtsen for helping me out on some of the following issues. He has a solution of his own inside the open source Balder project.

The answers to the questions:

“Does anyone know concrete examples of problems caused by not following the convention of naming the CLR property wrapper the same as the dependency property, or in other words, why is it of any importance?”

External tools may use this convention to access the dependency properties. I would argue these tools could be made smart enough to solve this without the convention, but since my proposed solution doesn’t require passing this name anymore at all, this is not an issue anymore.

“Why can I still use the dependency properties through XAML, without adding the field identifiers that end with the suffix ‘Property’?”

The XAML processor doesn’t use these identifiers directly, as the documentation on msdn might make you believe. However, again external tools, or future versions may follow this convention, so let’s assume it is required. Since I don’t own/use any of these tools I can’t verify this. Of real importance is the necessity for the properties to be registered in a static context. Luckily this makes the factory approach still a viable option.

The solution!

Taking all this new information into consideration, this is the best I could come up with:

public class FactoryExample : DependencyObject
{
    public enum Property
    {
        Standard,
        ReadOnly,   // This becomes a readonly property.
        Callback    // This property has callbacks assigned to it.
    }
    private static readonly DependencyPropertyFactory<Property> m_properties =
        new DependencyPropertyFactory<Property>();

    public static readonly DependencyProperty StandardProperty =
        m_properties[Property.Standard];
    public static readonly DependencyProperty ReadOnlyProperty =
        m_properties[Property.ReadOnly];
    public static readonly DependencyProperty CallbackProperty =
        m_properties[Property.Callback];

    [DependencyProperty(Property.Standard, DefaultValue="foo")]
    public string Standard
    {
        get { return m_properties.GetValue(this, Property.Standard) as string; }
        set { m_properties.SetValue(this, Property.Standard, value); }
    }

    [DependencyProperty(Property.ReadOnly)]
    public bool ReadOnly
    {
        get { return (bool)m_properties.GetValue(this, Property.ReadOnly); }
        private set { m_properties.SetValue(this, Property.ReadOnly, value); }
    }

    [DependencyProperty(Property.Callback)]
    public int Callback
    {
        get { return (int)m_properties.GetValue(this, Property.Callback); }
        set { m_properties.SetValue(this, Property.Callback, value); }
    }

    [DependencyPropertyChanged(Property.Callback)]
    public static void OnChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
        ...
    }

    [DependencyPropertyCoerce(Property.Callback)]
    public static object OnCoerce( DependencyObject d, object value )
    {
        ...
    }
}

As you might notice, not too many things have changed since the first post, but besides the advantages mentioned earlier, there are a couple of new features.

  • The owner type for the factory is automatically set to the outer class of the passed template parameter. You can still pass the type manually.
  • Exceptions are (optionally) thrown when the conventions aren’t followed. Thanks to the exceptions I actually found out one of my CLR property wrappers was set to protected (public is required), indicating a design flaw.
  • Behaviour of get and set is encapsulated inside the factory. (E.g. No need to know whether a dependency property is read only when using a private setter.)
  • Safe for obfuscation. (Before ID.ToString() was used, where ID was the enum value. Now the property name is used and the enum value is solely used to link things together.)

If you are anything like me, looking at the code you might think “This can still be improved!“. Unfortunately it looks like we reached the limitations of C#. What follows are some failed ideas I considered.

Requirement for an enum:

Why specify an enum, right? We already have the properties, why not use those as ID’s? In Einar’s implementation an expression tree is used as a way to represent the property by using a lambda expression, returning the property itself. (E.g. o => o.Standard) Unfortunately, expression trees can’t be passed as an argument to Attributes, required by the factory. Why? My guess is, “No particular reason.

AbstractDependencyObject:

Why not have an abstract class implement the factory by default? A default GetValue() and SetValue() method could be added, so “m_properties.GetValue(this, Property.Standard)” would be reduced to “GetValue(Property.Standard)”. Such an implementation would quickly turn out unusable as multiple inheritance isn’t supported.

Every property has almost the exact same implementation!:

Although macros can be nasty, I’d argue this would be a correct usage for them. But, ofcourse C# doesn’t support macros. The duplicate code was there before, at least it’s reduced and grouped together now.

So it looks like this is the end, …. or is it? Enter, Aspect Oriented Programming!

At first, a strangely unfamiliar name to me. Now, I can only dream of the following implementation.

[DependencyObject]
public class FactoryExample
{
    [DependencyProperty(DefaultValue="foo")]
    public string Standard { get; set; }

    [DependencyProperty]
    public bool ReadOnly { get; private set; }

    [DependencyProperty]
    public int Callback { get; set; }

    ...
}

By acquiring a license for PostSharp, or with a lot of free time on your hands by implementing it yourself, you could attempt an implementation just like that! If it whet your appetite, be sure to check it out, but for me, the road ends here.

Dependency Property Factory source code

For the latest version of this code, you can download my FCL Extension library. It’s located in the Whathecode.PresentationFramework assembly under the namespace Whathecode.System.Windows.DependencyPropertyFactory.

Dependency Property Factory – Part 2

This post is a follow-up to an earlier attempt to simplify creating dependency properties.

I didn’t notice a possible problem with the approach of the previous post since it doesn’t cause any problems in the project I use it in. WPF is quite strict when it comes to creating custom dependency properties. There are several ways in which you can do it wrong, and the code in the last post does admittedly, exactly that. “There are established naming conventions regarding dependency properties that you must follow in all but exceptional circumstances.” In my opinion, the ability to misuse an interface, and additionally not even being able to notice it, indicates a design flaw. To quote someone with a lot more experience:

Make interfaces easy to use correctly and hard to use incorrectly. The best way to prevent incorrect use is to make such use impossible. – Scott Meyers

…, and that’s exactly what I’ll try to do.

Convention 1: “The name of the field is always the name of the property, with the suffix Property appended.”

public static readonly DependencyProperty IsSpinningProperty =
    DependencyProperty.Register(
    "IsSpinning", typeof(Boolean), typeof(OwnerType));

Convention 2: “Define a CLR “wrapper” property whose name matches the name of the dependency property.”

public bool IsSpinning
{
    get { return (bool)GetValue(IsSpinningProperty); }
    set { SetValue(IsSpinningProperty, value); }
}

Convention 3: “In all but exceptional circumstances, your wrapper implementations should perform only the GetValue and SetValue actions, respectively.”

First I want to determine why ignoring these conventions causes problems. I was already aware that XAML bypasses property wrappers, resulting in convention 3, and proposed a solution in the previous post. An exception could be thrown in the factory class to prevent a wrong CLR property wrapper. Apparently XAML bypasses the wrappers by calling GetValue() and SetValue() directly (for performance reasons), using the property name with “Property” suffixed to it as a parameter. E.g. the property with the name “ABC” gets called as GetValue(ABCProperty). This causes convention 1. Convention 2 is a bit vague and not mentioned explicitly why it is necessary. Other problems when not following these conventions are according to msdn:

  • Certain aspects of styles and templates will not work.
  • Most tools and designers must rely on the naming conventions to properly serialize XAML, or to provide designer environment assistance at a per-property level.

Does anyone know concrete examples of problems caused by not following convention 2, or in other words, why is it of any importance?

The factory class mentioned in the previous post doesn’t follow convention 1 at all. Why can I still use the dependency properties through XAML? The setter and binding in the following sample work perfectly. It seems like all XAML really needs is the name of the dependency property as passed with the DependencyProperty.Register() method. This would also make a lot more sense, since the name would be redundant otherwise.

<DependencyPropertyTestControl
    XamlSetTest="100"
    Margin="{Binding RelativeSource={RelativeSource Self},
    Path=XamlSetTest}" />
    public class DependencyPropertyTestControl : Label
    {
        public enum Property
        {
            XamlSetTest
        }
        private static readonly DependencyPropertyFactory<Property> m_properties =
            new DependencyPropertyFactory<Property>( typeof( DependencyPropertyTestControl ) );

        public static readonly Dictionary<Property, DependencyProperty> Properties =
            m_properties.Properties;

        [DependencyPropertyAttribute( Property.XamlSetTest )]
        public string XamlSetTest
        {
            get { return GetValue( Properties[ Property.XamlSetTest ] ) as string; }
            set { SetValue( Properties[ Property.XamlSetTest ], value ); }
        }

        [DependencyPropertyChangedAttribute( Property.XamlSetTest )]
        public static void OnSourceChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
        {
            var control = d as DependencyPropertyTestControl;

            if ( control != null )
            {
                control.Content = e.NewValue;
            }
        }
    }

UPDATE:
I posted these questions on the msdn forum to see whether somebody could answer them. The answer seems to confirm my suspicions that the property system only uses the name passed to Register() and not the field identifier. I’m guessing it can access the dictionary of DependencyObject directly and uses the dependency property name as the key to find the property in this dictionary. Still it is not wise to break conventions, so I’ll attempt to adjust the factory so that it enforces them instead. I’m afraid this will make a lot of its code superfluous. Perhaps a helper class is a better approach. Recently I discovered exactly such an implementation, and will check it out.

Make Interfaces Easy to Use Correctly and Hard to Use Incorrectly

Dependency Property Factory

If you have ever developed an application using WPF, you most likely came across dependency properties. At first you love the flexibility of them and what it allows you to do, as they are great! However, after a while you might feel like you are writing a lot of duplicate code, and are filling up entire classes with it. This for me was a strong indication to encapsulate the behaviour and creation of dependency properties as good software design calls for.

To get a quick idea of my proposed solution I’ll simply post two code segments. One taken from an excellent tutorial on dependency properties by Christian Mosers. The other adjusts the code segment using the new approach.

Most common usage:

// Dependency Property
public static readonly DependencyProperty CurrentTimeProperty =
    DependencyProperty.Register(
        "CurrentTime",
        typeof(DateTime),
        typeof(MyClockControl),
        new FrameworkPropertyMetadata(
            DateTime.Now, OnCurrentTimePropertyChanged, OnCoerceTimeProperty
        ));

// .NET Property wrapper
public DateTime CurrentTime
{
    get { return (DateTime)GetValue(CurrentTimeProperty); }
    set { SetValue(CurrentTimeProperty, value); }
}

private static void OnCurrentTimePropertyChanged(
    DependencyObject source,
    DependencyPropertyChangedEventArgs e)
{
    MyClockControl control = source as MyClockControl;
    DateTime time = (DateTime)e.NewValue;
    // Put some update logic here...
}

private static object OnCoerceTimeProperty(DependencyObject sender, object data)
{
    if ((DateTime)data > DateTime.Now)
    {
        data = DateTime.Now;
    }
    return data;
}

// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey =
    DependencyProperty.RegisterReadOnly(
        "IsMouseOver",
        typeof(bool),
        typeof(MyClass),
        new FrameworkPropertyMetadata(false));

// Register the public property to get the value
public static readonly DependencyProperty IsMouseoverProperty =
    IsMouseOverPropertyKey.DependencyProperty;

// .NET Property wrapper
public int IsMouseOver
{
   get { return (bool)GetValue(IsMouseOverProperty); }
   private set { SetValue(IsMouseOverProperty, value); }
}

My proposed solution:

// Enum declaring all the dependency properties present.
public enum Property
{
    CurrentTime,
    IsMouseOver
}

// A factory class used to create and manage the dependency properties.
private static readonly DependencyPropertyFactory<Property> m_properties =
    new DependencyPropertyFactory<Property>(typeof(MyClockControl));

// Public dictionary used to access the dependency properties.
public static readonly Dictionary<Property, DependencyProperty> Properties =
    m_properties.Properties;

[DependencyPropertyAttribute(Property.CurrentTime, DefaultValue=DateTime.Now)]
public DateTime CurrentTime
{
    get { return (DateTime)GetValue(Properties[Property.CurrentTime]); }
    set { SetValue(Properties[Property.CurrentTime], value); }
}

[DependencyPropertyChangedAttribute(Property.CurrentTime)]
private static void OnCurrentTimePropertyChanged(
    DependencyObject source,
    DependencyPropertyChangedEventArgs e)
{
    MyClockControl control = source as MyClockControl;
    DateTime time = (DateTime)e.NewValue;
    // Put some update logic here...
}

[DependencyPropertyCoerceAttribute(Property.DateTime)]
private static object OnCoerceTimeProperty(DependencyObject sender, object data)
{
    if ((DateTime)data > DateTime.Now)
    {
        data = DateTime.Now;
    }
    return data;
}

[DependencyPropertyAttribute(Property.IsMouseOver)]
public bool IsMouseOver
{
   get { return (bool)GetValue(Properties[Property.IsMouseOver]); }
   private set {
       m_properties.SetReadOnlyProperty(this, Properties[Property.IsMouseOver], value);
   }
}

 

As you might notice, the last code sample has a few advantages.

  • To identify the dependency property an enum is used, still allowing for strong typed identification of the properties.
  • By passing the owner type for the dependency property to the factory class, it is specified in just one place.
  • The settings for a dependency property are placed right above the property which is used in code internally. Parameters you had to pass manually to the DependencyProperty.Register() method before are deduced automatically. You can still specify them manually as well.
  • Although not really visible through this short code sample, adding more properties is really easy and requires a lot less code.
  • Centralized code. In the unlikely event that the Register() method changes, you only have to adjust the code of the factory class.

How it works:
The factory uses reflection to analyse the code to which the attributes are applied. This way it knows the property type and whether the dependency property should be readonly or not. As a name for the property, the ToString() method is used by default.

To be fair I’ll also mention the problems I see with this approach:

  • There is a small overhead to retrieve the dependency property through the Dictionary every time. I do believe this will have a minor impact.
  • Since DependencyObject internally already works with a dictionary, it’s kind of a double effort.
  • The enum value needs to be defined three times for every property. I don’t know an immediate solution for this, but it is relevant for a future post where I’ll discuss data model generation.

Possible expansions:

  • Right now the Dictionary used to make the properties available for public use isn’t read only. Since this class isn’t available by default this might be a subject I’ll address at a later time. Googling for a short amount of time already indicated this is a known problem. Perhaps a custom implementation of Collection can be created to break all references to DependencyProperty.
  • Because the factory controls the creation of the dependency properties, exceptions can be thrown when invalid usage is detected. E.g. When the .NET properties contain more statements than the GetValue() and SetValue().

All things considered I don’t see any major disadvantages, but I’m no WPF expert. I’d love to have some input from people more experienced with WPF.

Factory source code

UPDATE:

Possible problems due to WPF’s naming conventions are discussed in a new post.
For the most recent version, go to my last post for information. For the source code, you can download my FCL Extension library. The DependencyPropertyFactory is located in the Whathecode.PresentationFramework assembly under the namespace Whathecode.System.Windows.DependencyPropertyFactory.