WPF:无法在用户控件中创建所有控件的实例

时间:2012-10-31 20:21:21

标签: wpf custom-controls

我在WPF应用程序中使用自定义控件。此自定义控件包括逻辑和资源字典。 在我的应用程序中,我有登录窗口和主窗口。应用程序首先加载登录窗口

<Application x:Class="Dest.App"
             ....
             StartupUri="Login.xaml">
</Application>

我在主窗口中使用的自定义控件

<time:Calendar CloseAppointment="OnDeleteAppointment" AddAppointment="OnAddAppointment" Appointments="{Binding Path=Model}" />

同样在MainWindow中我从程序集加载资源字典

<ResourceDictionary>
  <ResourceDictionary.MergedDictionaries>
    <ResourceDictionary Source="pack://application:,,,/WpfCalendar;component/Dictionary.xaml"/>
  </ResourceDictionary.MergedDictionaries>
</ResourceDictionary>

Visual Studio加载自定义控件,没有任何异常。但是当我加载应用程序并成功登录时,登录视图的viewmodel调用主窗口

 MainWindow mainWindow = new MainWindow();
 mainWindow.Show();

主窗口的构造函数

public MainWindow()
{
   InitializeComponent();    
   m_MainViewModel = new MainViewModel();
   this.DataContext = m_MainViewModel;
}

我收到例外

Exception

异常详情

  

在WpfCalendar.Logic.Calendar.FilterAppointments()中   d:\研发\牙科   软\ LotusScheduler \ WpfScheduler \ WpfCalendar \逻辑\ Calendar.cs:线   122点   WpfCalendar.Logic.Calendar.OnAppointmentsChanged(DependencyPropertyChangedEventArgs   e)在D:\ development \ Dental   软\ LotusScheduler \ WpfScheduler \ WpfCalendar \逻辑\ Calendar.cs:线   109点   WpfCalendar.Logic.Calendar.OnAppointmentsChanged(DependencyObject d,   DependencyPropertyChangedEventArgs e)在D:\ development \ Dental中   软\ LotusScheduler \ WpfScheduler \ WpfCalendar \逻辑\ Calendar.cs:线   100点   System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs   吃   System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs   吃   System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs   args)at   System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex   entryIndex,DependencyProperty dp,PropertyMetadata元数据,   EffectiveValueEntry oldEntry,EffectiveValueEntry&amp; newEntry,布尔值   coerceWithDeferredReference,Boolean coerceWithCurrentValue,   OperationType operationType)at   System.Windows.DependencyObject.InvalidateProperty(的DependencyProperty   dp,Boolean preserveCurrentValue)at   System.Windows.Data.BindingExpressionBase.Invalidate(布尔   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   尝试)   System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(布尔   lastChance)在MS.Internal.Data.DataBindEngine.Task.Run(布尔值   lastChance)在MS.Internal.Data.DataBindEngine.Run(Object arg)at   MS.Internal.Data.DataBindEngine.OnLayoutUpdated(对象发送者,   EventArgs e)at   System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()at   System.Windows.ContextLayoutManager.UpdateLayout()at   System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)   在System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()   在System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()at   System.Windows.Media.MediaContext.RenderMessageHandlerCore(对象   resizedCompositionTarget)at   System.Windows.Media.MediaContext.RenderMessageHandler(对象   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;处理)   MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,   IntPtr lParam,Boolean&amp;处理)   MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)at   System.Windows.Threading.ExceptionWrapper.InternalRealCall(代表   回调,对象args,Int32 numArgs)at   MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(对象   source,Delegate方法,Object args,Int32 numArgs,Delegate   catchHandler)at   System.Windows.Threading.Dispatcher.LegacyInvokeImpl(的DispatcherPriority   优先级,TimeSpan超时,委托方法,对象args,Int32   在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32)的numArgs)   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:\研发\牙科   Soft \ Lotus \ AMS \ Dentist \ ViewModel \ LoginingViewModel.cs:第162行   ViewModel.LoginingViewModel.b__0(Object param)in   d:\研发\牙科   Soft \ Lotus \ AMS \ Dentist \ ViewModel \ LoginingViewModel.cs:第115行at   ViewModel.CommonCommand.Execute(Object parameter)in   d:\研发\牙科   Soft \ Lotus \ AMS \ Dentist \ Commands \ CommonCommand.cs:第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)在System.Windows.UIElement.OnMouseLeftButtonUpThunk(对象发送者,   MouseButtonEventArgs e)at   System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(代表   genericHandler,Object genericTarget)at   System.Windows.RoutedEventArgs.InvokeHandler(委托处理程序,对象   目标)在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(代表   genericHandler,Object genericTarget)at   System.Windows.RoutedEventArgs.InvokeHandler(委托处理程序,对象   目标)在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 at   System.Windows.UIElement.RaiseEvent(RoutedEventArgs args,Boolean   在System.Windows.Input.InputManager.ProcessStagingArea()处于   System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)   在System.Windows.Input.InputProviderSite.ReportInput(InputReport   inputReport)at   System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd,   InputMode模式,Int32时间戳,RawMouseActions操作,Int32 x,   Int32 y,Int32 wheel)at   System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr的   hwnd,WindowMessage msg,IntPtr wParam,IntPtr lParam,Boolean&amp;   处理)   System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd,   Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&amp;处理)   MS.Win32.HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,   IntPtr lParam,Boolean&amp;处理)   MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)at   System.Windows.Threading.ExceptionWrapper.InternalRealCall(代表   回调,对象args,Int32 numArgs)at   MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(对象   source,Delegate方法,Object args,Int32 numArgs,Delegate   catchHandler)at   System.Windows.Threading.Dispatcher.LegacyInvokeImpl(的DispatcherPriority   优先级,TimeSpan超时,委托方法,对象args,Int32   在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32)的numArgs)   msg,IntPtr wParam,IntPtr lParam)at   MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg)at at   System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame   框架)   System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架)   在System.Windows.Threading.Dispatcher.Run()处   System.Windows.Application.RunDispatcher(Object ignore)at   System.Windows.Application.RunInternal(窗口窗口)at   System.Windows.Application.Run(窗口窗口)at   Dentist.App.Main()中的System.Windows.Application.Run()   d:\研发\牙科   Soft \ Lotus \ AMS \ Dentist \ obj \ x86 \ Debug \ App.g.cs:第0行   System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String []   args)在System.AppDomain.ExecuteAssembly(String assemblyFile,   证据assemblySecurity,String [] args)at   Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()at   System.Threading.ThreadHelper.ThreadStart_Context(Object state)at   System.Threading.ExecutionContext.RunInternal(执行上下文   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)at   System.Threading.ExecutionContext.Run(执行上下文   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)at   System.Threading.ExecutionContext.Run(执行上下文   executionContext,ContextCallback回调,对象状态)at   System.Threading.ThreadHelper.ThreadStart()

带有问题控件的资源字典的一部分

<Border BorderBrush="#A5BFE1" BorderThickness="0,1,1,1" Background="White" Grid.Column="1" Grid.Row="0" >
    <TextBlock x:Name="DayHeader" HorizontalAlignment="Center" VerticalAlignment="Center">
    <TextBlock.ToolTip>
        <ToolTip>
            <StackPanel>
                <TextBlock FontWeight="Bold" Text="{x:Static Properties:Resources.CalendarSelectedDayTitle}" />
                <TextBlock Text="{x:Static Properties:Resources.CalendarSelectedDayDescription}" />
            </StackPanel>
        </ToolTip>
    </TextBlock.ToolTip>
        </TextBlock>
</Border>
<time:Scroll x:Name="scrollViewer" CustomVerticalOffset="640.0" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="60" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <time:TimeRibbon Grid.Column="0"></time:TimeRibbon>
        <time:SchedulerDay Grid.Column="1" x:Name="Day"></time:SchedulerDay>
    </Grid>
</time:Scroll>

Calendar控件的构造函数(抛出异常)

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)));
}

但是当在app.xaml中设置第一个窗口MainWindow,而不是LoginWindow时,一切正常,没有任何例外!

请告知问题的原因是什么?

谢谢

1 个答案:

答案 0 :(得分:3)

您的FilterAppointments类构造函数中出现异常(根据您的屏幕截图)。您在其中根据您的controltemplate执行某些操作,但该时刻尚未分配模板。您应该重写OnApplyTemplate()并在那里移动该代码。