using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace DependencyPropertyExample
{
    // Example 18-20. Handling a change of template

    [TemplatePart(Name = "PART_Target", Type = typeof(FrameworkElement))]
    public class MyControl : Control
    {
        private FrameworkElement targetPart;

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            FrameworkElement oldTargetPart = targetPart;
            targetPart = Template.FindName("PART_Target", this) as FrameworkElement;
            if (!object.ReferenceEquals(oldTargetPart, targetPart))
            {
                if (oldTargetPart != null)
                {
                    oldTargetPart.MouseEnter -=
                        new MouseEventHandler(targetPart_MouseEnter);
                    oldTargetPart.MouseLeave -=
                        new MouseEventHandler(targetPart_MouseLeave);
                }

                if (targetPart != null)
                {
                    targetPart.MouseEnter +=
                        new MouseEventHandler(targetPart_MouseEnter);
                    targetPart.MouseLeave +=
                        new MouseEventHandler(targetPart_MouseLeave);
                }
            }
        }

        void targetPart_MouseLeave(object sender, MouseEventArgs e)
        {
        }
        void targetPart_MouseEnter(object sender, MouseEventArgs e)
        {
        }
    }

    // End of Example 18-20.

}
