Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic databinding

Tags:

c#

mvvm

wpf

xaml

How how do you do this in c#?

 <TextBlock Text={Binding MyProperty}/>

Assume the DataContext is set to a class of Type MyClass

like image 370
Jose Avatar asked Jun 11 '09 16:06

Jose


3 Answers

Assuming your TextBlock is called _textBlock:

var binding = new Binding("MyProperty");
BindingOperations.SetBinding(_textBlock, TextBlock.TextProperty, binding);
like image 56
Kent Boogaart Avatar answered Nov 20 '22 06:11

Kent Boogaart


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

like image 43
Andy Avatar answered Nov 20 '22 07:11

Andy


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.

like image 2
Qwertie Avatar answered Nov 20 '22 07:11

Qwertie