title: WPF: Cannot create an instance of all control in a user control
body: <p>I use custom control in my WPF application. This custom control includes logic and resource dictionary. 
  In my application I have login window and main window. Application first loads login window  </p>
  
  <pre><code>&lt;Application x:Class="Dest.App"
               ....
               StartupUri="Login.xaml"&gt;
  &lt;/Application&gt;
  </code></pre>
  
  <p>Custom control I use in my main window  </p>
  
  <pre><code>&lt;time:Calendar CloseAppointment="OnDeleteAppointment" AddAppointment="OnAddAppointment" Appointments="{Binding Path=Model}" /&gt;
  </code></pre>
  
  <p>Also in MainWindow I load resource dictionary from assembly  </p>
  
  <pre><code>&lt;ResourceDictionary&gt;
    &lt;ResourceDictionary.MergedDictionaries&gt;
      &lt;ResourceDictionary Source="pack://application:,,,/WpfCalendar;component/Dictionary.xaml"/&gt;
    &lt;/ResourceDictionary.MergedDictionaries&gt;
  &lt;/ResourceDictionary&gt;
  </code></pre>
  
  <p>Visual Studio loads custom control without any exceptions. But when I load application and successfully login, viewmodel of the login view calls main windows  </p>
  
  <pre><code> MainWindow mainWindow = new MainWindow();
   mainWindow.Show();
  </code></pre>
  
  <p>Constructor of the main window  </p>
  
  <pre><code>public MainWindow()
  {
     InitializeComponent();    
     m_MainViewModel = new MainViewModel();
     this.DataContext = m_MainViewModel;
  }
  </code></pre>
  
  <p>I receive an exception  </p>
  
  <p><a href="http://oi48.tinypic.com/11ljskh.jpg" rel="nofollow">Exception</a>
  <br /></p>
  
  <p>Exception details </p>
  
  <blockquote>
    <p>at WpfCalendar.Logic.Calendar.FilterAppointments() in
    D:\development\Dental
    Soft\LotusScheduler\WpfScheduler\WpfCalendar\Logic\Calendar.cs:line
    122 at
    WpfCalendar.Logic.Calendar.OnAppointmentsChanged(DependencyPropertyChangedEventArgs
    e) in D:\development\Dental
    Soft\LotusScheduler\WpfScheduler\WpfCalendar\Logic\Calendar.cs:line
    109 at
    WpfCalendar.Logic.Calendar.OnAppointmentsChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e) in D:\development\Dental
    Soft\LotusScheduler\WpfScheduler\WpfCalendar\Logic\Calendar.cs:line
    100 at
    System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs
    e) at
    System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs
    e) at
    System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs
    args) at
    System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex
    entryIndex, DependencyProperty dp, PropertyMetadata metadata,
    EffectiveValueEntry oldEntry, EffectiveValueEntry&amp; newEntry, Boolean
    coerceWithDeferredReference, Boolean coerceWithCurrentValue,
    OperationType operationType) at
    System.Windows.DependencyObject.InvalidateProperty(DependencyProperty
    dp, Boolean preserveCurrentValue) at
    System.Windows.Data.BindingExpressionBase.Invalidate(Boolean
    isASubPropertyChange) at
    System.Windows.Data.BindingExpression.TransferValue(Object newValue,
    Boolean isASubPropertyChange) at
    System.Windows.Data.BindingExpression.Activate(Object item) at
    System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt
    attempt) at
    System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean
    lastChance) at MS.Internal.Data.DataBindEngine.Task.Run(Boolean
    lastChance) at MS.Internal.Data.DataBindEngine.Run(Object arg) at
    MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender,
    EventArgs e) at
    System.Windows.ContextLayoutManager.fireLayoutUpdateEvent() at
    System.Windows.ContextLayoutManager.UpdateLayout() at
    System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
    at System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
    at System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks() at
    System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object
    resizedCompositionTarget) at
    System.Windows.Media.MediaContext.RenderMessageHandler(Object
    resizedCompositionTarget) at
    System.Windows.Media.MediaContext.Resize(ICompositionTarget
    resizedCompositionTarget) at
    System.Windows.Interop.HwndTarget.OnResize() at
    System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg,
    IntPtr wparam, IntPtr lparam) at
    System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd,
    Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled) at
    MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam,
    IntPtr lParam, Boolean&amp; handled) at
    MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at
    System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
    callback, Object args, Int32 numArgs) at
    MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object
    source, Delegate method, Object args, Int32 numArgs, Delegate
    catchHandler) at
    System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
    priority, TimeSpan timeout, Delegate method, Object args, Int32
    numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32
    msg, IntPtr wParam, IntPtr lParam) at
    MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr
    hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at
    MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr hwnd, Int32 msg, IntPtr
    wParam, IntPtr lParam) at
    MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr
    hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at
    MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr
    wParam, IntPtr lParam) at
    MS.Win32.UnsafeNativeMethods.SetWindowPos(HandleRef hWnd, HandleRef
    hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Int32 flags) at
    System.Windows.Window.SetupInitialState(Double requestedTop, Double
    requestedLeft, Double requestedWidth, Double requestedHeight) at
    System.Windows.Window.CreateSourceWindow(Boolean duringShow) at
    System.Windows.Window.CreateSourceWindowDuringShow() at
    System.Windows.Window.SafeCreateWindowDuringShow() at
    System.Windows.Window.ShowHelper(Object booleanBox) at
    System.Windows.Window.Show() at
    ViewModel.LoginingViewModel.Login(Object parameter) in
    D:\development\Dental
    Soft\Lotus\AMS\Dentist\ViewModel\LoginingViewModel.cs:line 162 at
    ViewModel.LoginingViewModel.b__0(Object param) in
    D:\development\Dental
    Soft\Lotus\AMS\Dentist\ViewModel\LoginingViewModel.cs:line 115 at
    ViewModel.CommonCommand.Execute(Object parameter) in
    D:\development\Dental
    Soft\Lotus\AMS\Dentist\Commands\CommonCommand.cs:line 59 at
    MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource
    commandSource, Boolean userInitiated) at
    System.Windows.Controls.Primitives.ButtonBase.OnClick() at
    System.Windows.Controls.Button.OnClick() at
    System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs
    e) at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender,
    MouseButtonEventArgs e) at
    System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate
    genericHandler, Object genericTarget) at
    System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object
    target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object
    target, RoutedEventArgs routedEventArgs) at
    System.Windows.EventRoute.InvokeHandlersImpl(Object source,
    RoutedEventArgs args, Boolean reRaised) at
    System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender,
    RoutedEventArgs args, RoutedEvent newEvent) at
    System.Windows.UIElement.OnMouseUpThunk(Object sender,
    MouseButtonEventArgs e) at
    System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate
    genericHandler, Object genericTarget) at
    System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object
    target) at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object
    target, RoutedEventArgs routedEventArgs) at
    System.Windows.EventRoute.InvokeHandlersImpl(Object source,
    RoutedEventArgs args, Boolean reRaised) at
    System.Windows.UIElement.RaiseEventImpl(DependencyObject sender,
    RoutedEventArgs args) at
    System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args) at
    System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean
    trusted) at System.Windows.Input.InputManager.ProcessStagingArea() at
    System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
    at System.Windows.Input.InputProviderSite.ReportInput(InputReport
    inputReport) at
    System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd,
    InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x,
    Int32 y, Int32 wheel) at
    System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr
    hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean&amp;
    handled) at
    System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd,
    Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled) at
    MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam,
    IntPtr lParam, Boolean&amp; handled) at
    MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at
    System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate
    callback, Object args, Int32 numArgs) at
    MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object
    source, Delegate method, Object args, Int32 numArgs, Delegate
    catchHandler) at
    System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority
    priority, TimeSpan timeout, Delegate method, Object args, Int32
    numArgs) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32
    msg, IntPtr wParam, IntPtr lParam) at
    MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg) at
    System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame
    frame) at
    System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
    at System.Windows.Threading.Dispatcher.Run() at
    System.Windows.Application.RunDispatcher(Object ignore) at
    System.Windows.Application.RunInternal(Window window) at
    System.Windows.Application.Run(Window window) at
    System.Windows.Application.Run() at Dentist.App.Main() in
    D:\development\Dental
    Soft\Lotus\AMS\Dentist\obj\x86\Debug\App.g.cs:line 0 at
    System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
    args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
    Evidence assemblySecurity, String[] args) at
    Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at
    System.Threading.ThreadHelper.ThreadStart_Context(Object state) at
    System.Threading.ExecutionContext.RunInternal(ExecutionContext
    executionContext, ContextCallback callback, Object state, Boolean
    preserveSyncCtx) at
    System.Threading.ExecutionContext.Run(ExecutionContext
    executionContext, ContextCallback callback, Object state, Boolean
    preserveSyncCtx) at
    System.Threading.ExecutionContext.Run(ExecutionContext
    executionContext, ContextCallback callback, Object state) at
    System.Threading.ThreadHelper.ThreadStart()</p>
  </blockquote>
  
  <p>Part of the resource dictionary with problem controls  </p>
  
  <pre><code>&lt;Border BorderBrush="#A5BFE1" BorderThickness="0,1,1,1" Background="White" Grid.Column="1" Grid.Row="0" &gt;
      &lt;TextBlock x:Name="DayHeader" HorizontalAlignment="Center" VerticalAlignment="Center"&gt;
      &lt;TextBlock.ToolTip&gt;
          &lt;ToolTip&gt;
              &lt;StackPanel&gt;
                  &lt;TextBlock FontWeight="Bold" Text="{x:Static Properties:Resources.CalendarSelectedDayTitle}" /&gt;
                  &lt;TextBlock Text="{x:Static Properties:Resources.CalendarSelectedDayDescription}" /&gt;
              &lt;/StackPanel&gt;
          &lt;/ToolTip&gt;
      &lt;/TextBlock.ToolTip&gt;
          &lt;/TextBlock&gt;
  &lt;/Border&gt;
  &lt;time:Scroll x:Name="scrollViewer" CustomVerticalOffset="640.0" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2"&gt;
      &lt;Grid&gt;
          &lt;Grid.ColumnDefinitions&gt;
              &lt;ColumnDefinition Width="60" /&gt;
              &lt;ColumnDefinition Width="*" /&gt;
          &lt;/Grid.ColumnDefinitions&gt;
  
          &lt;time:TimeRibbon Grid.Column="0"&gt;&lt;/time:TimeRibbon&gt;
          &lt;time:SchedulerDay Grid.Column="1" x:Name="Day"&gt;&lt;/time:SchedulerDay&gt;
      &lt;/Grid&gt;
  &lt;/time:Scroll&gt;
  </code></pre>
  
  <p>Constructor of the Calendar control (that throw exception)  </p>
  
  <pre><code>public Calendar()
  {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(Calendar), new FrameworkPropertyMetadata(typeof(Calendar)));
  
      CommandManager.RegisterClassCommandBinding(typeof(Calendar), 
          new CommandBinding(NextDay, new ExecutedRoutedEventHandler(OnExecutedNextDay), 
              new CanExecuteRoutedEventHandler(OnCanExecuteNextDay)));
  
      CommandManager.RegisterClassCommandBinding(typeof(Calendar),
          new CommandBinding(PreviousDay, new ExecutedRoutedEventHandler(OnExecutedPreviousDay),
              new CanExecuteRoutedEventHandler(OnCanExecutePreviousDay)));
  }
  </code></pre>
  
  <p>But when set in app.xaml the first window MainWindow, not LoginWindow everything works properly without any excetions!  </p>
  
  <p>Please advise what can be cause of the problem?  </p>
  
  <p>Thank you  </p>