65.9K
CodeProject is changing. Read more.
Home

WPF : TemplateBinding in code

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Aug 14, 2011

CPOL
viewsIcon

33813

Many people i have noticed are struggling to use templatebinding in code using TemplateBindingExtension or TemplateBindingExpression and get the error : “TemplateBindingExtension’ is not valid for Setter.Value. The only supported MarkupExtension types are DynamicResourceExtension and BindingBase or derived types” Instead you can simple use binding as follows :
var textblock = new TextBlock();
textblock.Background = Brushes.Blue;
textblock.Text = "saraf";

var binding = new Binding("Background");
binding.RelativeSource = new RelativeSource(RelativeSourceMode.Self);
BindingOperations.SetBinding(textblock, TextBlock.ForegroundProperty, binding);

//just to show the textblock.
var window = new Window();
window.Content = textblock;
window.ShowDialog();
Also if you want to do the same but bind to the TemplatedParent, simply use RelativeSourceMode.TemplatedParent