2013-05-07 5 views
2

그래서 기본적으로 MainWindow, 클래스 SetupViewModel은 별도의 cs 파일에 정의되어 있고 또 다른 클래스 ImageViewModel은 별도의 cs 파일에 있습니다. 어쨌든 ImageViewModel에서 MainWindow의 작업을 호출 할 수 있는지 궁금합니다. 자세한 내용은 아래 :스레드가 주 창을 호출합니까?

private int _viewType; 
    public int ViewType 
    { 
     get 
     { 
      return _viewType; 
     } 
     set 
     { 
      _viewType = value; 
      OnPropertyChanged("ViewType"); 
     } 
    } 
다음과 같이

this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, 
       new Action(
        delegate() 
        { 
          ((SetupViewModel)this.DataContext).ViewType = Convert.ToInt32(ViewTypes.ViewType2D); 
        } 
       ) 
      ); 
  • ViewType 변수 SetupViewModel에 정의되어 ImageViewModel에

    • 은 (MainWindow에서 다음 코드)은 다음과 같이 MainWindow를 변화 호출

    • 다음은 내가 한 방법이지만 성공하지 못했습니다. ImageViewModel의 호출 코드 :

      { 액션 SwitchTo2DView = 대리자를() 시도 { ((CaptureSetupViewModel) System.Windows.Application.Current.MainWindow.DataContext) .ViewType = Convert.ToInt32 (ViewTypes.ViewType2D) ; };

        System.Windows.Application.Current.MainWindow.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, SwitchTo2DView); 
           } 
           catch (Exception ex) 
           { 
            Console.WriteLine("Caught exception: " + ex.ToString()); 
           } 
      

  • 과 예외 : 나는 C 번호에 평신도입니다

    System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object. 
        at CaptureSetupDll.ViewModel.LiveImageViewModel.<StartZStackPreview>b__2c() 
        --- End of inner exception stack trace --- 
        at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
        at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) 
        at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) 
        at System.Delegate.DynamicInvokeImpl(Object[] args) 
        at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) 
        at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
        at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
        at System.Windows.Threading.DispatcherOperation.InvokeImpl() 
        at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) 
        at System.Threading.ExecutionContext.runTryCode(Object userData) 
        at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) 
        at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) 
        at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
        at System.Windows.Threading.DispatcherOperation.Invoke() 
        at System.Windows.Threading.Dispatcher.ProcessQueue() 
        at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
        at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 
        at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 
        at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) 
        at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
        at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) 
        at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) 
        at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) 
        at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 
        at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 
        at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 
        at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) 
        at System.Windows.Threading.DispatcherOperation.Wait(TimeSpan timeout) 
        at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) 
        at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method) 
        at CaptureSetupDll.ViewModel.LiveImageViewModel.StartZStackPreview() 
    

    ; 내가 어떻게이 일을 할 수 있는지 아는가? 고마워.

    +0

    의 InnerException 및 스택 추적 무엇입니까? – SLaks

    +0

    어떻게 찾을 수 있습니까? –

    +0

    Visual Studio가 열려있는 동안 표시되는 예외 창에서이 정보를 제공합니다. 두 번째 스레드에서 MainWindow를 호출하는 올바른 방법입니다. –

    답변

    3

    귀하의 DataContext가 호출 될 때 5 달러가 걸릴 것입니다. 아마 너무 일찌기 부름 받았음을 의미합니다. 아마도 Dispatcher에서하는 일을 무엇이든 추진해야한다는 뜻입니다.

    이 응용 프로그램은이 메서드가 호출 될 때 완전히로드되지만 실제로는 그렇지 않을 수도 있습니다. 이를 테스트하려면 디버깅 중에 중단 점을 설정하고 DataContext이 null인지 확인하십시오.

    null 인 경우 두 가지 선택 사항이 있습니다. 첫째, 돌아 오십시오. 메서드가 호출되는 방법에 따라로드하는 동안 메서드가 여러 번 호출 될 수 있습니다. 이후의 호출은 null 이외의 문맥을 나타낼 가능성이 있습니다.

    다른 옵션은 응용 프로그램이로드 된 후 Dispatcher을 사용하여 나중에 메서드를 다시 호출하는 것입니다.

    여기 가지의 C#처럼 보이는 심지어 컴파일 할 수있는 작은 의사는 다음과 같습니다

    public void CheckTheDataContext() 
    { 
        // is it null? 
        if(this.DataContext == null) 
        { 
         // then drop an Action re-invoking this method later 
         // when the application idles out a bit 
         Dispatcher.BeginInvoke((Action)(() => 
         { 
          CheckTheDataContext(); 
         }), System.Windows.Threading.DispatcherPriority.ApplicationIdle); 
         return; 
        } 
        DoSomethingElseWithTheContext(DataContext); 
    } 
    
    +1

    그건 완전히 의미가 있습니다. 윌에게 고마워. :) –