I have this in XAML
<ControlTemplate TargetType="{x:Type Button}">
<Image ...>
</ControlTemplate>
I want to achieve same in C# code. How can I achieve this?
ControlTemplate ct = new ControlTemplate();..
Image img = new Image();..
Now how to assign this Image to Control template? Can we do this or Am I missing any concept here?
If you need to change the button image only then you can do one thing.
Now in XAML use this in button template
On property Change of CurrentButtonImage update the image of button (in code behind) using
Creating template in codebehind is not a good idea, in theory one would do this by defining the
ControlTemplate.VisualTree
which is aFrameworkElementFactory
.Assigning properties is very roundabout since you need to use
SetValue
andSetBinding
:Also, about the (previously) accepted answer and the stuff quoted:
That statement is just wrong, we do not "have to".
If i assign templates at run time i define them as a resource which i can load if i need it.
Edit: According to the documentation
FrameworkElementFactory
is deprecated:I wonder if this recommendation is such a good idea. Personally i would still go with defining the template as a resource in XAML if i can avoid doing it with strings and the
XamlReader
.http://www.eggheadcafe.com/sample-code/SilverlightWPFandXAML/73fdb6a2-6044-4c43-8766-afa12618ddc1/set-controltemplate-programmatically.aspx