首页 文章

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

提问于
浏览
0

我在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:\开发\ Dental Soft \ LotusScheduler \ WpfScheduler \ WpfCalendar \ Logic \ Calendar.cs:D:\ development \ Dental Soft \ LotusScheduler \ WpfScheduler \ WpfCalendar \ Logic中WpfCalendar.Logic.Calendar.OnAppointmentsChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)的第109行\ Calendar.cs:在System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)上System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)上System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs参数)在System.Windows.DependencyObject线100 . UpdateEffectiveValue(EntryIndex entryIndex,DependencyProperty dp,PropertyMetadata metadata,EffectiveValueEntry oldEntry,EffectiveValueEntr y&newEntry,Boolean coerceWithDeferredReference,Boolean coerceWithCurrentValue,OperationType operationType)System.Windows.DeinddencyObject.InvalidateProperty(DependencyProperty dp,Boolean preserveCurrentValue),位于System.Windows.Data.BindingExpression的System.Windows.Data.BindingExpressionBase.Invalidate(Boolean isASubPropertyChange) . TransferValue(对象NEWVALUE,布尔isASubPropertyChange)在System.Windows.Data.BindingExpression.Activate(对象项)在System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt尝试)在System.Windows.Data.BindingExpression.MS.Internal.Data .IDataBindEngineClient.AttachToContext(布尔最后机会)在MS.Internal.Data.DataBindEngine.Task.Run(布尔最后机会)在MS.Internal.Data.DataBindEngine.Run(对象ARG)在MS.Internal.Data.DataBindEngine.OnLayoutUpdated(对象发件人,EventArgs e)在System.Windows.Contex上的System.Windows.ContextLayoutManager.UpdateLayout()处的System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()处系统中的System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)中的System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()处的System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()处的tLayoutManager.UpdateLayoutCallback(Object arg) . Windows.Media.MediaContext.RenderMessageHandler(对象resizedCompositionTarget)在System.Windows.Media.MediaContext.Resize(ICompositionTarget resizedCompositionTarget)在System.Windows.Interop.HwndTarget.OnResize()在System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage MSG位于MS.Win32.HwndWrapper.WndProc的System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&handling)中的IntPtr wparam,IntPtr lparam(IntPtr hwnd,Int32 msg,IntPtr wParam)在System.Windows.Threading.ExceptionWrapper.InternalRealCall的MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)中,IntPtr lParam,Boolean&handling)(委托回调,Object args, (INT32 numArgs)在MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen对象源,委托方法,对象指定参数时,INT32 numArgs,代表catchHandler)在System.Windows.Threading.Dispatcher.LegacyInvokeImpl(的DispatcherPriority优先权,时间 Span 超时,委托方法,对象在MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc,IntPtr hWnd,Int32 msg,IntPtr wParam,IntPtr lParam)的MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam)的args,Int32 numArgs)在MS.Win32处的MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam)MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc,IntPtr hWnd,Int32 msg,IntPtr wParam,IntPtr lParam) . HwndSubclass.SubclassWndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtrLPARAM)在MS.Win32.UnsafeNativeMethods.SetWindowPos(HandleRef的hWnd,HandleRef hWndInsertAfter,的Int32的x,的Int32 Y,的Int32 CX,CY的Int32,的Int32标志)在System.Windows.Window.SetupInitialState(双requestedTop,双requestedLeft,双requestedWidth,在System.Windows.Window.CreateSourceWindow(Boolean duringShow)上的System.Windows.Window.CreateSourceWindowDuringShow()处的System.Window.Window.SafeCreateWindowDuringShow()处于System.Windows.Window.SafeHelper(Object booleanBox)处 . Windows.Window.Show()在ViewModel.LogindViewModel.Login(Object参数)的D:\ development \ Dental Soft \ Lotus \ AMS \ Dentist \ ViewModel \ LoginingViewModel.cs:第162行,ViewModel.LoginingViewModel.b__0(对象参数)在D:\ development \ Dental Soft \ Lotus \ AMS \ Dentist \ ViewModel \ LoginingViewModel.cs:第115行,位于D:\ development \ Dental Soft \ Lotus \ AMS \ Dentist \ Commands \中的ViewModel.CommonCommand.Execute(Object parameter) CommonCommand.cs:MS.Internal.Commands.CommandHelpers.Crit中的第59行icalExecuteCommandSource(ICommandSource commandSource,布尔用户引发)在System.Windows.Controls.Primitives.ButtonBase.OnClick()在System.Windows.Controls.Button.OnClick()在System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs E)在System.Windows.UIElement.OnMouseLeftButtonUpThunk(对象发件人,MouseButtonEventArgs e)上System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(代表genericHandler,对象genericTarget)在系统在System.Windows.RoutedEventArgs.InvokeHandler(委托处理程序,对象目标) . 系统中的System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender,RoutedEventArgs args,RoutedEvent newEvent)上的System.Windows.EventRoute.InvokeHandlersImpl(Object source,RoutedEventArgs args,Boolean reRaised)中的Windows.RoutedEventHandlerInfo.InvokeHandler(Object target,RoutedEventArgs routedEventArgs) System.Windows.Input.MouseButtonEventAr中的.Windows.UIElement.OnMouseUpThunk(Object sender,MouseButtonEventArgs e) System.Windows.EventRoute.InvokeHandlersImpl(Object)上的System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target,RoutedEventArgs routedEventArgs)中的System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler,Object target)中的gs.InvokeEventHandler(Delegate genericHandler,Object genericTarget)在System.Windows.Uindlement.RaiseEvent的System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)上的System.Windows.UIElement.RaiseEventImpl(DependencyObject sender,RoutedEventArgs args)中的Source,RoutedEventArgs args,Boolean reRaised)(RoutedEventArgs args,Boolean trusted)在System.Windows.Input.InputManager.ProcessStagingArea()在System.Windows.Input.InputManager.ProcessInput(InputEventArgs输入)在System.Windows.Input.InputProviderSite.ReportInput(inputReport inputReport)在System.Windows.Interop.HwndMouseInputProvider.ReportInput System.Windows.Interop.HwndMouseI上的(IntPtr hwnd,InputMode模式,Int32时间戳,RawMouseActions操作,Int32 x,Int32 y,Int32轮)位于MS.Win32的System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&handling)的nputProvider.FilterMessage(IntPtr hwnd,WindowMessage msg,IntPtr wParam,IntPtr lParam,Boolean&handling) . 在System.Windows.Threading.ExceptionWrapper.InternalRealCall的MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)中的HwndWrapper.WndProc(IntPtr hwnd,Int32 msg,IntPtr wParam,IntPtr lParam,Boolean&handling)(委托回调,Object args,Int32 numArgs )在MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(对象源,委托方法,对象指定参数时,的Int32 numArgs,代表catchHandler)在System.Windows.Threading.Dispatcher.LegacyInvokeImpl(的DispatcherPriority优先权,时间 Span 超时,委托方法,对象指定参数时, INT32 numArgs)在MS.Win32.HwndSubclass.SubclassWndProc(IntPtr的HWND,INT32味精,IntPtr的wParam中,IntPtr的LPARAM)在MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&MSG)在System.Windows.Threading.Dispatcher.PushFr System.Windows.Application上的System.Windows.Application.RunDispatcher(Object ignore)处的System.Windows.Threading.Dispatcher.Run()处的System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame框架)中的ameImpl(DispatcherFrame框架) . System.Windows.Application.Run(窗口窗口)中的System.Windows.Application.Run(窗口窗口)中的RunInternal(窗口窗口)位于D:\ development \ Dental Soft \ Lotus \ AMS \ Dentist \中Dentist.App.Main()的System.Windows.Application.Run() obj \ x86 \ Debug \ App.g.cs:第0行System.Threading.ThreadHelper上的Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()中的System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)中的System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,String [] args) System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)中的.ThreadStart_Context(Object state),位于系统的System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,Object state,Boolean preserveSyncCtx) System.Threading.ThreadHelper.ThreadStart()中的.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)

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

<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 回答

  • 3

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

相关问题