如何从主窗口执行函数

问题描述:

我正在用C#开发一个WPF小游戏。我同时打开2个窗口,一个窗口显示player1和一个窗口显示player2。如何从主窗口执行函数

现在我想在player2的窗口中点击一个按钮时在player1中启动一个函数。

Player1 play1 = new Player1(); 
play1.Function(); 

然后执行第三个新窗口中的函数:

我试了一下。但我想在第一个现有的窗口中执行它。那我该怎么做?

+0

保留对'Player2'中的'Player1'窗口的引用。 –

+0

恩,我该怎么做? – Cortana

+0

将它传递给你的'Player2'窗口。使用'Player1'类型的参数创建一个构造函数。 –

你有更多的选择如何做到这一点。 一个在此链接中解释:link

其他是从父窗口传递引用到子窗口。

您在Player2窗口中定义属性PLAYER1像:

public class Player2 { 
    public Player1 Parent {private set;get} 

    public Player2(Player1 parent) { 
     this.Parent = parent; 
    } 

    public void MyMethod() { 
     Parent.CustomMethodCall(); 
    } 
} 

您创建PLAYER1窗口Player2对象,如:

var win = new Player2(this); 
win.ShowDialog(); 
+0

非常感谢你!链接工作正常。但是你的代码解决方案对我没有任何作用。 – Cortana

我会做的是使用事件从主窗口进行沟通子窗口。并在子窗口中监听主窗口的方法。

你有你的PlayerWindow就像你公开一些事件的地方。我也交锋在另一个方向的通信方法(主窗口 - >播放器窗口)

public class PlayerWindow : window 
{ 
    public event EventHandler UserClickedButton; 

    //Here the function you call when the user click's a button 
    OnClick() 
    { 
     //if someone is listening to the event, call it 
     if(UserClickedButton != null) 
      UserClieckedButton(this, EventArgs.Empty); 
    } 

    public void ShowSomeStuff(string stuff) 
    { 
     MyLabel.Content = stuff; 
    } 
} 

然后你有你的主窗口中,创建两个窗口(每个人)和监听事件

public class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     //we create the first window 
     PlayerWindow w1 = new PlayerWindow(); 
     //hook to the event 
     w1.UserClickedButton += Player1Clicked; 

     //same for player 2 
     PlayerWindow w2 = new PlayerWindow(); 
     w2.UserClickedButton += Player2Clicked; 

     //open the created windows 
     w1.Show(); 
     w2.Show(); 
    } 

    private void Player2Clicked(object sender, EventArgs e) 
    { 
     //Here your code when player 2 clicks. 
     w1.ShowSomeStuff("The other player clicked!"); 
    } 

    private void Player2Clicked(object sender, EventArgs e) 
    { 
     //Here your code when player 1 clicks. 
     w2.ShowSomeStuff("The player 1 clicked!"); 
    } 
}