【问题标题】:How to make the WPF app to, open only one new window or create only single instance of the XAML, when clicking button in MainWindow?单击 MainWindow 中的按钮时,如何使 WPF 应用程序仅打开一个新窗口或仅创建 XAML 的单个实例?
【发布时间】:2019-06-27 04:38:44
【问题描述】:

我有一个 WPF 应用程序,这是应用程序结构:

观看次数

MainWindow.xaml、ABC.xaml(都带有 .cs 文件)

视图模型

MainWindowVM.cs、ABCVM.cs

我在 MainWindow.xaml 中有一个按钮(绑定到 MainWindowVM.cs),它调用 MainWindowVM.cs中的 SampleFunction() 函数> 当被单击时,SampleFunction() 会创建一个新的 ABC.xaml 实例(绑定到 ABCVM.cs)并打开一个新的 ABC 窗口。 xaml 使用 Show() 函数。

如何确保在旧窗口仍然存在时单击 MainWindow 中的按钮不会打开 ABC.xaml 的另一个新窗口,或者不会创建 ABC 的另一个新实例.xaml?

MainWindow.xaml.cs

public partial class MainWindow : Window
{
    /*...Some other codes...*/

    private MainWindowVM _VM = new MainWindowVM();
    public MainWindowVM MainWindowVM 
    { 
        get { return _VM; } 
        set { _VM= value; } 
    }
    public MainWindow()
    {
       InitializeComponent();
       this.DataContext = MainWindowVM;      
    }
    private void SomeControl_MouseLeftButtonUp(object sender,MouseButtonEventArgs e)
    {
       MainWindowVM.SampleFunction();
    }
}

MainWindowVM.cs

public class MainWindowVM
{
    /*...Some other codes...*/

     public void SampleFunction()
     {
         ABC abc= new ABC();
         abc.Show();
     }
}

ABC.xaml.cs

public partial class ABC: Window
{
    /*...Some other codes...*/

    private static ABCVM _abcVM= new ABCVM();
    public ABCVM ABCVM { get { return _abcVM; } set { _abcVM = value; } }
    public ABC()
    {
       InitializeComponent();
       this.DataContext = ABCVM;
    }
}

【问题讨论】:

  • 我不确定我是否正确理解了您的问题。但是您可以使用 ShowDialog() 而不是 Show()。然后你必须先关闭 ABC.xaml,然后才能在 MainWindow 上做点什么(例如打开另一个 ABC)
  • @Presi 是的,这就是解决方案。谢谢。
  • 我将其发布为答案。请接受它,每个人都能快速看到解决方案。

标签: c# wpf xaml


【解决方案1】:

使用 ShowDialog() 代替 Show()。

然后您必须先关闭 ABC.xaml,然后才能在 MainWindow 上进行操作。所以你不能打开第二个 ABC.xaml 窗口。

【讨论】:

    【解决方案2】:

    您可以编写代码来检查窗口类型对象是否存在。

                for each(Window win in Application.Current.Windows)
                {
                    string windowType = win.GetType().ToString();
                    if (!windowType.Equals(nameSpace + "." + ABC))
                    {
                       ABC abc= new ABC();
                       abc.Show();
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 1970-01-01
      • 2014-12-21
      • 1970-01-01
      • 2019-04-12
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      相关资源
      最近更新 更多