How to set Control Template in code?

前端 未结 3 1959
滥情空心
滥情空心 2020-12-01 12:05

I have this in XAML


    

I want to achieve

3条回答
  •  死守一世寂寞
    2020-12-01 12:43

    Creating template in codebehind is not a good idea, in theory one would do this by defining the ControlTemplate.VisualTree which is a FrameworkElementFactory.

    ControlTemplate template = new ControlTemplate(typeof(Button));
    var image = new FrameworkElementFactory(typeof(Image));
    template.VisualTree = image;
    

    Assigning properties is very roundabout since you need to use SetValue and SetBinding:

    image.SetValue(Image.SourceProperty, ...);
    

    Also, about the (previously) accepted answer and the stuff quoted:

    Setting the ControlTemplate programmatically is just like using XAML because we have to use the XamlReader class.

    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:

    This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.

    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.

提交回复
热议问题