22

i am trying to binding a very simple property to a TextBlock, but I have to do all in code-behind (C#).

What i am trying to do is:

public string SomeText { get; set; }

And after I try the Binding on TextBlock:

Binding myBinding = new Binding(SomeText);
myTextBlock.SetBinding(TextBlock.TextProperty, myBinding);

How do I keep the Text property of the TextBlock the same of the Property SomeText.

cdbitesky
  • 1,390
  • 1
  • 13
  • 30
Diego Vieira
  • 843
  • 2
  • 8
  • 13
  • `Binding myBinding = new Binding(SomeText);` sould be `Binding myBinding = new Binding("SomeText");` Just quote `SomeText`. – Fredrick Gauss Nov 10 '22 at 06:28

1 Answers1

47

Use BindingOperations

Binding binding = new Binding();
binding.Path = new PropertyPath("SomeText");
binding.Source = sourceObject;  // view model?

BindingOperations.SetBinding(theTextBlock, TextBlock.TextProperty, binding);
Phil
  • 42,255
  • 9
  • 100
  • 100
  • 4
    FrameworkLement has [a wrapper](http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.setbinding.aspx) for that, it would be shorter. The only problem here was the setting of the binding path. – H.B. Apr 12 '12 at 21:58