Silverlight Binding Catastrophe

You can tell it's the first day back after a 2 week vacation/holiday/beer-and-food-fuelled-break when it takes you an hour to work out why something like this isn't working... but on reflection, I decided that this was actually very tricky to spot once I'd made the original blooper, and nothing showed up when I "binged" it, so I'll record my embarrassing error here for the benefit of anyone that searches in the future.

I have been creating Silverlight 3 bindings in code using something like this;

var binding = new System.Windows.Data.Binding();

binding.Mode = BindingMode.OneWay;

binding.Source = this.MyGrid;

binding.Path = new PropertyPath(text);

ResultText.SetBinding(TextBox.TextProperty, binding);

In this example, MyGrid is just a grid with some extra content defined in XAML (what content is irrelevant), and ResultText is a TextBlock that displays the result of the binding. "text" is a variable holding a valid property path.

Can you spot the mistake yet? Every time I ran this, no matter what the content of "text" was I got the nasty exception that reads;

Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))

Owch. If I created the binding using XAML syntax with the same property path it worked fine... so what was my mistake? I specified a Dependency Property for TextBox when creating the binding accidentally instead of TextBlock (I was using both at one point so you see how easily this happened). My corrected code with highlighted change is below;

ResultText.SetBinding(TextBlock.TextProperty, binding);

So the moral of the story is that if you get a catastrophic error when creating a Silverlight binding programmatically ensure that the Dependency Property you're specifying really is found on the type you're binding to.

I hope that helps someone out. And don't tell anyone I made this embarrassing error J