【问题标题】:Update current instance of Window from another class, rather than the newly created C# WPF从另一个类而不是新创建的 C# WPF 更新 Window 的当前实例
【发布时间】:2019-09-02 10:05:30
【问题描述】:

我正在尝试在 Window 的当前实例上使用 BeginAnimation,但什么也没发生,因为它使用的是我刚刚创建的实例。

我已经阅读了使用 DataContext 的其他答案,但这些答案的目标是访问文本框的属性,我认为它不适用于这里。

EditSql.xaml.cs

    {
        MainWindow main = new MainWindow();
        e.Cancel = true;
        Application.Current.MainWindow.Visibility = Visibility.Hidden;
        main.RestoreAfterEditClose();
    }

MainWindow.xaml.cs

    public void RestoreAfterEditClose()
    {
        Grid2.BeginAnimation(OpacityProperty, instant1);    // not working
        this.ManageGrid.BeginAnimation(OpacityProperty, instant1);   // not working
        Create_A_Visit.Foreground = Brushes.Red; // not working
    }

MainWindow.xaml.cs

我知道问题是它在新创建的 main 而不是当前实例上启动动画,但不知道如何修复。这可能是面包和黄油的东西,但最好能很好地了解它的工作原理。

编辑

问题是这样的,因为我正在创建一个名为 main 的新 MainWindow 实例,当我将 RestoreAfterEditClose 类称为 main.RestoreAfterEditClose()时,它不会对我以前隐藏的 MainWindow 生效(显然,我'已经通过执行 main.Show() 证明了这一点,并看到更改在那里生效)。

尝试澄清我正在尝试做的事情。我正在尝试找到一种方法在我当前的 MainWindow 实例上从另一个类调用 RestoreAfterEditClose,但我不知道如何。

问题:有没有在不创建 MainWindow 的新实例的情况下调用另一个类的方法?

完整方法

EditSql.xaml.cs

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
        MainWindow main = new MainWindow();
        main.Show();
        main.RestoreAfterEditClose();
        e.Cancel = true;
        Application.Current.MainWindow.Visibility = Visibility.Hidden;         
    }

【问题讨论】:

  • 您的MainWindow。仍然是Hidden。必须是 Visible 才能看到 Opacity 的变化。
  • 不清楚你在做什么。您必须调用 main.Show() 才能使新实例可见。
  • 什么是instant1?请提供完整的上下文。不要在这里开始智力竞赛。
  • @BionicCode 我添加了一个编辑。 instant1 只是将不透明度更改为 1。

标签: c# wpf


【解决方案1】:

您在新窗口上调用 RestoreAfterEditClose。如果你想在另一个窗口上做,你必须在那里调用它。

您可以使用((MainWindow)Application.Current.MainWindow) 或通过获取控件的父窗口:Window.GetWindow(this) 来访问当前主窗口。

【讨论】:

  • 我已经尝试了上述方法,但仍然没有。为了澄清,我在我的窗口EditSQL 上调用RestoreAfterEditClose(),但没有一个动画从MainWindow 开始。我误解了你的解决方案吗?
  • 那么instant1一定是错的。那必须是您要在其上执行动画的实例。因为这是一个窗口上的方法,所以逻辑上它是'this',或者是'this'的控件。
  • 正如我在回答中所解释的,有几种方法可以访问主窗口。只需调用右侧窗口的方法,而不是创建一个不需要的新窗口。我建议在线查找一些基本的 C# 教程以了解类实例的概念。如果你不这样做,你会在尝试和失败中浪费更多的时间。
  • 是的,我没有创建一个我不需要的窗口。 Window 正在使用中,整个类是 Window 关闭时的事件。无论如何,我会将您的答案标记为正确,我会找到另一种方法。
  • 我已经在底部添加了完整的方法
猜你喜欢
  • 2023-04-02
  • 2016-08-25
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2011-12-17
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
相关资源
最近更新 更多