How to set Control Template in code?

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

I have this in XAML


    

I want to achieve

3条回答
  •  春和景丽
    2020-12-01 12:27

    http://www.eggheadcafe.com/sample-code/SilverlightWPFandXAML/73fdb6a2-6044-4c43-8766-afa12618ddc1/set-controltemplate-programmatically.aspx

    Setting the ControlTemplate programmatically is just like using XAML because we have to use the XamlReader class. For example, here is the code to set a button's template, assuming that we want to set a button's template after it is loaded.

    private void Button_Loaded(object sender, RoutedEventArgs e) {
        var button = sender as Button;
        string template =
            "" +
                "" +
                     "" +
                "" +
            "";
        button.Template = (ControlTemplate)XamlReader.Parse(template);
    }
    

    Since we used a string for specifying the XAML code for the template, we can use the XamlReader's Parse method. The XamlReader also has a Load method, which is primarily used for streams or XAML or XML readers. Notice that we have to include the XML namespace http://schemas.microsoft.com/winfx/2006/xaml/presentation because the ControlTemplate, Border, and other controls we need are defined there. If we did not include it, we'll encounter a runtime exception. Basically, we have to put the namespaces needed by the template.

提交回复
热议问题