在 windows 之间传递对象

Pass objects between windows

我试图将对象传递给下一个 window,但我收到了 Null 异常。 所以在我的第一个 window:

        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 绝对不为空。

第二个window:

    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>

异常消息:{"Object reference not set to an instance of an object."}

堆栈跟踪:

   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 异常。我尝试使用参数创建新的 window。第一个 MainWindow class 试图调用构造函数,在构造函数之后它将参数设置为对象。只要我在构造函数完成之前使用这个对象,它就会给我 null 异常。

如果您对名称进行 "ToString()",这是否意味着 "Name" 的类型已经不是字符串?如果是这样的话,那么我想你应该给它一个值,或者至少实例化它?

第143行,是什么?

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

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

 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
      //...
      }
    }

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

您是否考虑过研究消息传递框架?例如 MVVMLight、Jounce 或任何其他 MVVM 框架中包含的框架?但是,推出您自己的事件聚合器并不困难。您必须有一种机制让 windows 都能获得事件聚合器的实例;通过某种服务定位器或依赖注入框架,甚至将其创建为 属性 主应用 class.

使用消息传递,您实际上是从第一个 window 发送一条消息,第二个 window 会收听它。

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