在窗口之间传递对象

时间:2015-01-22 23:39:42

标签: c# wpf

我试图将对象传递给下一个窗口,但是我得到了一个N​​ull异常。 所以在我的第一个窗口中:

        private void Button_Ok_Click(object sender, RoutedEventArgs e)
        {
           if (file == null)
           {
              System.Windows.MessageBox.Show("null");
              return;
           }
           MainWindow wnd = new MainWindow
           {
              myFileInfo = file
           };
           if(wnd.myFileInfo == null)
              System.Windows.MessageBox.Show("null2");
           wnd.Show();
        }

MessegeBox没有显示,因此filewnd.myFileInfo绝对不为空。

第二个窗口:

    public partial class MainWindow : Window
    {
      public FileInfo myFileInfo;
      //...
      public MainWindow()
      {
          InitializeComponent();
          LabelFileName.Content = "File Name: " + this.myFileInfo.Name.ToString(); // Null exception
      //...
      }
    }

我尽我所能找到解决方案,遗憾的是不成功。

XAML:

<Grid>
    <Label Name="LabelFileName" Grid.Column="0" Grid.Row="0" />
</Grid>

异常消息:{“对象引用未设置为对象的实例。”}

堆栈追踪:

   at Charts.MainWindow..ctor() in c:\Users\Daniel\Documents\Visual Studio 2012\Projects\Charts\Charts\MainWindow.xaml.cs:line 143
   at Charts.Init.Button_Ok_Click(Object sender, RoutedEventArgs e) in c:\Users\Daniel\Documents\Visual Studio 2012\Projects\Charts\Charts\Init.xaml.cs:line 84
   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.RaiseEvent(RoutedEventArgs e)
   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& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(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, 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& 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 Charts.App.Main() in c:\Users\Daniel\Documents\Visual Studio 2012\Projects\Charts\Charts\obj\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()

好的,我理解为什么它会给我null异常。我尝试用参数创建新窗口。第一个MainWindow类试图调用构造函数,在构造函数之后它会将参数设置为object。只要我在构造函数之前使用这个对象就可以了,显然​​它会给我null异常。

3 个答案:

答案 0 :(得分:1)

您是否考虑过调查消息框架?比如MVVMLight,Jounce或任何其他MVVM框架中包含的那些?但是,滚动自己的事件聚合器并不困难。您必须为两个窗口都有一个机制来获取事件聚合器的实例;通过某种服务定位器或依赖注入框架,或者甚至创建它作为主应用程序类的属性。

通过消息传递,您实际上是从第一个窗口发送消息,而第二个窗口会监听它。

在您的方案中,单击按钮会显示窗口,然后发布消息。收到消息后的第二个窗口将能够根据其内容采取行动。

答案 1 :(得分:0)

如果您在名称上执行“ToString()”,这是否意味着“名称”的类型不是字符串?如果是这种情况,那么我猜你应该给它一个值,或至少实例化它?

第143行,它是什么?

Eeesh。在该行上放置一个断点,将鼠标悬停在每个对象和属性上,找出什么是null。这让我烦恼,我想知道!

答案 2 :(得分:0)

你能否为第二个窗口添加辅助构造函数?然后将对象传递给构造函数。

 public partial class MainWindow : Window
    {
      public FileInfo myFileInfo;
      //...
public MainWindow(FileInfo theInfo)
{
InitializeComponent();
myFileInfo = theInfo;
}

      public MainWindow()
      {
          InitializeComponent();
          LabelFileName.Content = "File Name: " + this.myFileInfo.Name.ToString(); // Null exception
      //...
      }
    }

然后在创建新窗口时,传入文件信息对象。