public class MyControl : Control { private Button _button; public MyControl() { DefaultStyleKey = typeof(MyControl); } public override void OnApplyTemplate() { base.OnApplyTemplate(); _button = GetTemplateChild("PART_Button") as Button; if (_button != null) { _button.Click += OnButtonClick; } } private void OnButtonClick(object sender, RoutedEventArgs e) { // Apply a new control template ApplyTemplate(); } }
public class MyControl : Control { private TextBlock _textBlock; public MyControl() { DefaultStyleKey = typeof(MyControl); } public override void OnApplyTemplate() { base.OnApplyTemplate(); _textBlock = GetTemplateChild("PART_TextBlock") as TextBlock; } private void OnButtonClick(object sender, RoutedEventArgs e) { if (_textBlock != null) { // Update the text block's properties _textBlock.Text = "Hello, world!"; _textBlock.Foreground = Brushes.Red; } } }The example code snippets above demonstrate how the FrameworkElement.ApplyTemplate method can be used to modify the appearance of custom controls in response to user interaction events. The package library for this method is the "System.Windows" library.