Click here to Skip to main content
13,191,400 members (80,771 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 14 Aug 2011

WPF : TemplateBinding in code

, 14 Aug 2011
Rate this:
Please Sign up or sign in to vote.
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;

Also if you want to do the same but bind to the TemplatedParent, simply use



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Saraf Talukder
Software Developer
United Kingdom United Kingdom
Currently living and working in London. He is an enthusiastic software developer passionate about microsoft technologies, specially C#, WPF, Silverlight WCF and windows Azure. Contributes to several open source project and msdn forums.

My Blog
twitter : @sarafuddin

You may also be interested in...


Comments and Discussions

GeneralYou can avoid the magic string in the binding by using the N... Pin
Richard Deeming19-Aug-11 7:17
memberRichard Deeming19-Aug-11 7:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171017.1 | Last Updated 14 Aug 2011
Article Copyright 2011 by Saraf Talukder
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid