Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Silverlight: Programmatically binding control properties

The big picture: I have a custom child control that generates various textboxes, datepickers, combo etc based on properties that I set. This control is embedded in various places within my SL application.

I generally use the MVVM pattern, and I want to bind the values of these dynamic controls back into my master page view model.

I always know that there will be 8 controls on the form so I can have dependency properties in place for the controls to bind to. Then the controls that reference this control, can use binding with the data that has been entered whilst maintaining an MVVM pattern.

The question: How can I bind the values of dynamic controls to dependency properties programmatically?

Thanks, Mark

like image 461
Mark Cooper Avatar asked Jul 14 '09 16:07

Mark Cooper


2 Answers

Lets assume you have created a simple TextBox dynamically and you want to add a binding on the Text property:-

 Binding binding = new Binding("SomeProperty");
 binding.Mode = BindingMode.TwoWay;

 txtBox.SetBinding(TextBox.TextProperty, binding);

Where txtBox is the dynamically created TextBox you want to observe/mutate.

like image 132
AnthonyWJones Avatar answered Sep 28 '22 08:09

AnthonyWJones


Mark, I'm not entirely sure I've understood the implications in your question, but have you considered the Binding class? For example:

Customer customer = new Customer();
TextBox box = new TextBox();
Binding binding = new Binding("FullName");
binding.Source = customer;
box.SetBinding(TextBox.TextProperty, binding);

This binds the "Text" dependency property of the TextBox control to the "FullName" property of the customer object.

like image 40
Ben M Avatar answered Sep 28 '22 07:09

Ben M