2016-05-17 94 views
0

我正在用C#開發一個WPF小遊戲。我同時打開2個窗口,一個窗口顯示player1和一個窗口顯示player2。如何從主窗口執行函數

現在我想在player2的窗口中點擊一個按鈕時在player1中啓動一個函數。

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

然後執行第三個新窗口中的函數:

我試了一下。但我想在第一個現有的窗口中執行它。那我該怎麼做?

+0

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

+0

恩,我該怎麼做? – Cortana

+0

將它傳遞給你的'Player2'窗口。使用'Player1'類型的參數創建一個構造函數。 –

回答

1

你有更多的選擇如何做到這一點。 一個在此鏈接中解釋: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

0

我會做的是使用事件從主窗口進行溝通子窗口。並在子窗口中監聽主窗口的方法。

你有你的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!"); 
    } 
}