如何从主窗口执行功能

时间:2016-05-17 12:51:14

标签: c# wpf multithreading window

我正在使用C#在WPF中开发一个小游戏。我有2个Windows同时打开,一个窗口用于player1,一个窗口用于player2。

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

我尝试过:

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

然后它在第三个新窗口中执行该功能。但我想在第一个现有窗口中执行它。那我怎么能这样做呢?

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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!");
     }
}
相关问题