如何从另一个窗口调用MainWindow方法?

我需要从另一个窗口中的 MainWindow 调用方法。问题是我不知道为什么会出现错误,我想修复它。


我尝试使用各种方式调用该函数,但没有一个起作用。这是我最后一次尝试:


我想打电话:


namespace Class1

{

    public partial class MainWindow : Window

    {

        ...

        public void SkipVideo()

        {

            ...

        }

    }

}

这是我尝试拨打电话的方式:


namespace Class1

{

    public partial class TimeWindow : Window

    {

        ...

        private void DemoVideo_MediaEnded(object sender, RoutedEventArgs e)

        {

            ((MainWindow)Application.Current.MainWindow).SkipVideo();

        }

    }

}

没有构建错误,但是当我运行该程序时,它会执行以下操作: System.InvalidCastException: 'Unable to cast object of type 'Class1.TimeWindow' to type 'Class1.MainWindow'.'


HUX布斯
浏览 111回答 3
3回答

12345678_0001

这InvalidCastException意味着您的应用程序的主窗口是TimeWindow.如果确实有一个MainWindowopen,你可以像这样获取它的引用:private void DemoVideo_MediaEnded(object sender, RoutedEventArgs e){&nbsp; &nbsp; MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();&nbsp; &nbsp; if (mainWindow != null)&nbsp; &nbsp; &nbsp; &nbsp; mainWindow.SkipVideo();}有更好的方法来处理这个问题,例如使用 @Christopher 建议的 MVVM 设计模式,但这可能是考虑到您当前设置的最简单的方法。

江户川乱折腾

- 只是你应该在 MainWindow 类中执行此代码:&nbsp; &nbsp; public partial class MainWindow : Window&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public static MainWindow _instance;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; public MainWindow()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _instance = this;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InitializeComponent();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }private void SkipVideo(){}&nbsp; &nbsp; }- 现在你可以调用任何方法、用户控件等:public partial class TimeWindow : Window{&nbsp; &nbsp; ...&nbsp; &nbsp; private void DemoVideo_MediaEnded(object sender, RoutedEventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; MainWindow._instance.SkipVideo();&nbsp; &nbsp; }}

FFIVE

需要向实例TimeWindow传递对mainWindow实例的引用,以调用mainWindow.SkipVideo(). 通常,当您TimeWindow在mainWindow. TimeWindow 中的公共属性或构造函数参数可用于提交实例。但是,您使用的是 WPF,这是一种 Windows 窗体编程方法。WPF/UWP 的设计考虑了 MVVM 模式。这不是 MVVM 模式。虽然您可以使用旧方法,但这样做会错过 WPF 大约 90% 的功能,并且在其他各个方面都会遇到问题。如果你打算在 WPF 中工作,你肯定需要学习 MVVM。MVVM 包括一种像这样跨 Windows 共享数据/功能的方法。
打开App,查看更多内容
随时随地看视频慕课网APP