UserControl с Caliburn.Micro в ElementHost форм - PullRequest
0 голосов
/ 14 июля 2020

Я новичок в Caliburn.Micro .. Я пытаюсь разработать WPF UserControl и буду использовать его в Forms ElementHost. Это должен быть WPF, потому что позже я буду использовать его в приложении WPF.

Моя проблема в том, что я не знаю, как использовать Caliburn.Micro в моем UserControl. Есть ли какой-нибудь пример?

Могу ли я создать ResourceDictionary, который ссылается на Bootstrapper в моем UserControl xaml?

Спасибо за вашу помощь!

Дополнение:

Я нашел кое-что в документации caliburn.micro:

Caliburn.Micro можно использовать с хостов, отличных от Xaml. Чтобы выполнить sh это, вы должны выполнить несколько иную процедуру, поскольку ваше приложение не запускается через App.xaml. Вместо этого создайте собственный ускоритель, унаследовав его от BoostrapperBase (не-generi c версия). При наследовании вы должны передать «false» параметру «useApplication» базового конструктора. Это позволяет загрузчику правильно настраивать Caliburn.Micro без наличия экземпляра приложения Xaml. Все, что вам нужно сделать, чтобы запустить фреймворк, - это создать экземпляр вашего Bootstrapper и вызвать метод Initialize (). После создания экземпляра класса вы можете использовать Caliburn.Micro как обычно, возможно, вызвав IWindowManager для отображения нового пользовательского интерфейса.

Итак, я отредактировал свой Bootstrapper

 public class Bootstrapper : BootstrapperBase
        {
         private static BootstrapperBase bootstrapper;
    
         public Bootstrapper() : base(false)
         {
                
            Initialize();
         }
    
            //protected override void OnStartup(object sender, StartupEventArgs e)
            //{
            //    DisplayRootViewFor<ShellViewModel>();
            //}
        }

И я вызвать конструктор в коде моего wpf userControl.

Теперь я получаю следующую ошибку:

bei System.Activator.CreateInstance(Type type, Boolean nonPublic)
   bei System.Activator.CreateInstance(Type type)
   bei Caliburn.Micro.BootstrapperBase.GetInstance(Type service, String key)
   bei Caliburn.Micro.Action.SetTargetCore(DependencyPropertyChangedEventArgs e, DependencyObject d, Boolean setContext)
   bei Caliburn.Micro.Action.OnTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   bei System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   bei System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   bei System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   bei System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   bei System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   bei System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   bei Caliburn.Micro.ViewModelBinder.<>c.<.cctor>b__10_3(Object viewModel, DependencyObject view, Object context)
   bei Caliburn.Micro.Bind.<>c__DisplayClass7_0.<ModelChanged>b__0(Object <sender>, RoutedEventArgs <e>)
   bei Caliburn.Micro.View.<>c__DisplayClass8_0.<ExecuteOnLoad>b__0(Object s, RoutedEventArgs e)
   bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   bei System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   bei System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   bei System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObject root, RoutedEvent routedEvent)
   bei System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root)
   bei MS.Internal.LoadedOrUnloadedOperation.DoWork()
   bei System.Windows.Media.MediaContext.FireLoadedPendingCallbacks()
   bei System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   bei System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   bei System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   bei System.Windows.Threading.DispatcherOperation.InvokeImpl()
   bei System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   bei MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
   bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   bei MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   bei System.Windows.Threading.DispatcherOperation.Invoke()
   bei System.Windows.Threading.Dispatcher.ProcessQueue()
   bei System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   bei MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   bei MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   bei System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   bei MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   bei System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   bei System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   bei System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   bei System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   bei System.Windows.Forms.Application.Run(Form mainForm)

Roman

...