【问题标题】:pass window as variable, wpf将窗口作为变量传递,wpf
【发布时间】:2010-08-07 07:29:02
【问题描述】:

提前感谢您的帮助。

在位于 Main() 的以下代码中: Application.Run(新的 frmBackground(frmExit)) 我正在尝试启动窗口 frmBackground,它将窗口作为构造函数中的参数,并且在加载所有内容(背景图像)之后,它然后启动传递的窗口。但是,这不会编译,仅在我使用时编译 Application.Run(新 frmBackground(新 frmExit())) 它传递了正确的窗口参数,但它自己创建了一个 frmExit 实例并启动窗口,即使启动窗口的 frmBackground 代码被注释掉。

再次感谢您。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    据我了解,当您说 Application.Run(new frmBackground(frmExit)) 时,您传递的不是frmExit 的实例,而是类型(类),据我了解,您的方法是期望的一个实例...您可能想要执行以下操作:

    frmExit exitForm = new frmExit();
    Application.Run(new frmBackground(exitForm));
    

    或者有一些“包”类,你可以在其中保留一些你知道你可能需要的资源的引用,比如这个表单的引用 (frmExit),并更改 frmBackground 的构造函数,然后你替换对参数变量与您的“包”类上的值..类似的东西..

    如果这不是您想要实现的目标,我建议您在此处提供代码的更多详细信息

    【讨论】:

    • 原来的 Application.Run(new frmBackground(new frmExit)) 确实传递了一个 frmExit 的实例
    • 感谢您的回复。我已经尝试过这种方法,它会导致完全相同的行为。我不想传递窗口的实例(它导致它显示),只是将窗口作为稍后实例化的类型。我希望我不会太困惑。
    • 那么你在frmBackground的构造函数上使用了错误的签名......如果你只是想稍后实例化,为什么不创建一个可以传递类型的属性或方法(比如frmExit,为此,您必须强制该类型必须继承自 frmExit 所做的同一类型),然后应用工厂来创建该类型的实例?
    • 我希望 frmBackground 接受一个窗口类型,而不指定对 frmExit 的任何显式引用,因为 frmBackground 将在许多项目中使用,其中大多数项目不知道 frmExit。我在 frmBackground 中尝试了一种属性方法,但无法使其正常运行。您能否提供解释您的方法的代码 sn-p。干杯! frmBackground: public Window w { set { value = new Window(); value.ShowDialog(); } } 主要:frmBackground w = new frmBackground();应用程序.运行(w); w.w = (type)frmExit;
    【解决方案2】:

    将 Type 传递给构造函数,然后使用反射在您的 frmBackground 中创建它

    这将告诉你如何

    Create an instance of a Type, provided as a parameter to a method

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 2016-12-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2018-06-21
      相关资源
      最近更新 更多