Set ControlTemplate Programmatically

By Michael Detras

Usually, we use XAML to specify templates for our controls like Button and TextBox. However, there may be some times when we need to do it programmatically or via code.

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 =
        "<ControlTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' TargetType=\"Button\">" +
            "<Border>" +
                 "<ContentPresenter/>" +
            "</Border>" +
        "</ControlTemplate>";
    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.

Set ControlTemplate Programmatically  (4558 Views)