开发者

How does a method in a winform listen to an event/delegate in App_Code, and not get a null event?

开发者 https://www.devze.com 2023-03-18 15:09 出处:网络
Scenario - Program opens a winForm.User enters info, clicks Start button.Action transfers to code in App_Code.Model.When that code finishes, code behind the winForm needs to display updated informat

Scenario -

Program opens a winForm. User enters info, clicks Start button. Action transfers to code in App_Code.Model. When that code finishes, code behind the winForm needs to display updated information. App_Code.Model shouldn't know about the winForm. The winForm in this case has a button btnStart and a textbox tbInput.

But when the event is raised, it is null, so I am doing something wrong. Note, this is not about events raised from winForms userControls, I am aware there is a lot of information online about that.

App_Code.Model using System; using System.Collections.Generic; using System.Linq; using System.Text;

namespace EventsTest.App_Code.Model
{
    public delegate void TableViewChangeHandler(object sender, HandChangedEventArgs e);

    public class HandChangedEventArgs : EventArgs{
        public int HandNum { get; set; }
        public int PlayerNum { get; set; }
        public HandChangedEventArgs(int handNum, int playerNum){
            HandNum = handNum;
            PlayerNum = playerNum;
        }
    }
    public class Game{
        public event TableViewChangeHandler TableViewChanged;
        public void PrepareGame(){
            int value = -1;
            if (TableViewChanged != null)
                TableViewChanged(this, new HandChangedEventArgs(value, 0));
            else
                value = 2;//used to set toggle to catch debugger
        }
    }
}

code behind form using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using EventsTest.App_Code.Model;

namespace EventsTest
{
    public partial class testForm : Form{
        public testForm(){
            InitializeComponent();
            Game myGame = new Game();
            myGame.TableViewChanged += this.HandleTableViewChange;
        }
        private void btnStart_Click(object sender, EventArgs e) {
            Game myGame = new Game();
            myGame.PrepareGame();
        }
        public void HandleTableViewChange(object sender, HandChang开发者_运维知识库edEventArgs e){
            this.tbInput.Text = "Raised";
        }
    }
}


May be I understand. You have two instances of Game class:

  1. Is in ctor of the form and subscribes to the event.

  2. Is in btnStart_Click method which doesn't subscribe to event and call PrepareGame(), so you don't recieve event notification.

MOve your event subaceiption code to button click handler and you done.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号