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
Comments
Anonymous
January 04, 2010
If only all errors were that simple to debug- the fun ones are when you go and create new sample app after new sample app to test your code, typing it the correct way every time in your tests, before you realize your typo in the original application. :) Otherwise good tip and a good reminder to check and make sure you're using the right properties in cases like this!Anonymous
January 07, 2010
The comment has been removedAnonymous
January 14, 2010
Great - that's exactly why I blogged it so I'm pleased to hear it was useful. SimonAnonymous
May 13, 2010
Hi Simon - I also wanted to say thank you this one bit me today as well and this helped me. :-)Anonymous
June 08, 2010
Hi, thank you. I had just the same problem :)Anonymous
December 01, 2012
After one hour of debuging I said, lets search on the web. Thank you Simon for this. This saved me many more hours - I wouldn't have spoted otherwise.Anonymous
January 18, 2013
Thanks man! I was using Control.BorderThickness, but I had to use Border.BorderThickness