tags:

views:

246

answers:

3

How how do you do this in c#?

 <TextBlock Text={Binding MyProperty}/>

Assume the DataContext is set to a class of Type MyClass

+2  A: 

You can call FrameworkElement.SetBinding() to build data binding from C#.

Andy
+3  A: 

Assuming your TextBlock is called _textBlock:

var binding = new Binding("MyProperty");
BindingOperations.SetBinding(_textBlock, TextBlock.TextProperty, binding);

HTH, Kent

Kent Boogaart
Seconded. I've used the code Kent describes here in LOB apps, and it works perfectly. Take care to set the Mode property of the binding object if the target of the binding doesn't support TwoWay by default.
Mark
When do you call this? in the constructor? does it matter?
Jose
You call it when you want there to be a binding between the control and data. Generally that's in the constructor, but it certainly could be elsewhere.
Kent Boogaart
+1  A: 

Simple:

<TextBlock x:Name="txt"/>

// C#
txt.SetBinding(TextBox.TextProperty, "MyProperty");

Create a Binding object and pass it to SetBinding if you want more control over the binding.

Qwertie