Custom Control Initialization exception <p>I have a custom windows control that inherits from <code>Window</code> class which I am trying to use in my other project. I have overwritten the <code>OnInitialized()</code> method inside my custom window class. My problem is <code>base.OnInitialized();</code> line, that's where I get <code>object reference not set to an instance of the of the object</code> exception. Here is my custom windows class:</p> <pre><code> public class MacWindow : Window { public HwndSource HwndSource { get { return _hwndSource; } } private HwndSource _hwndSource; MacWindowBehaviour behaviour; protected override void OnInitialized(EventArgs e) { SourceInitialized += OnSourceInitialized; base.OnInitialized(e); } private void OnSourceInitialized(object sender, EventArgs e) { _hwndSource = (HwndSource)PresentationSource.FromVisual(this); } static MacWindow() { //This is done so that the control automatically finds the fallback style in Generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(MacWindow), new FrameworkPropertyMetadata(typeof(MacWindow))); } public MacWindow() : base() { behaviour = new MacWindowBehaviour(this); PreviewMouseMove += behaviour.MacWindow_PreviewMouseMove; } public override void OnApplyTemplate() { //assigns the event handlers for Window panel buttons when windows is loaded Button minButton = GetTemplateChild("minimizeButton") as Button; Button restButton = GetTemplateChild("restoreButton") as Button; Button clButton = GetTemplateChild("closeButton") as Button; minButton.Click += behaviour.MinimizeClick; restButton.Click += behaviour.RestoreClick; clButton.Click += behaviour.CloseClick; Grid resizeGrid = GetTemplateChild("resizeGrid") as Grid; foreach (UIElement element in resizeGrid.Children) { Rectangle rect = element as Rectangle; rect.MouseMove += behaviour.rect_MouseMove; rect.MouseLeftButtonDown += behaviour.rect_MouseLeftButtonDown; } base.OnApplyTemplate(); } } </code></pre>