views:

2302

answers:

2

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

+2  A: 

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.

AnthonyWJones
I suppose there should be assignment to binding.Source. Otherwise, it doesn't bind anything.
Morgan Cheng
+3  A: 

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.

Ben M
And as AnthonyWJones pointed out, you'd need to set BindingMode.TwoWay if you want changes in the TextBox to propagate back to the customer object.
Ben M
You probably don't want to assign the source at this level though would you?
AnthonyWJones
Yeah, probably not -- since that overrides the DataContext.
Ben M
Thanks for the answer. I have +1'd you, but awarded the answer to Anthony for the information on TwoWay mode which is more inline with what I needed. Mark
Mark Cooper