Programmatic binding in Silverlight

2020-07-09 08:06发布

问题:

I'm missing the boat on something here, kids. This keeps rearing its head and I don't know what's going on with it, so I hope my homeys here can help.

When working in Silverlight, when I create bindings in my c# code, they never hold up when the application is running. The declarative bindings from my xaml seem ok, but I'm doing something wrong when I create my bindings in C#. I'm hoping that there is something blindingly obvious I'm missing. Here's a typical binding that gets crushed:

TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);

回答1:

I've just tried the exact code you just posted and it worked fine, with some changes. I believe the problem is the element you are using for the SetBinding call is not the textblock you want to bind. It should be:

TextBlock tb = new TextBlock();
Binding b = new Binding("FontSize");
b.Source = this;
tb.SetBinding(TextBlock.FontSizeProperty, b);

Make sure you also have a FontSize public property of type double on "this". If "this" is a user control, I would recommend renaming the property so you don't hide the inherited member.



回答2:

It looks like as of Silverlight 3.1, at least, this is no longer an issue. I can't reproduce it, at any rate.