【问题标题】:Delegate/Events winform c# is not working - subscriber/listener is always null委托/事件 winform c# 不起作用 - 订阅者/侦听器始终为空
【发布时间】:2015-10-29 02:16:24
【问题描述】:

我有一个用户控件,它以 win 形式添加(它是动态添加的)。在另一个类中,我有属性,并且我有该属性的事件,当它更新时,通知项目的其他部分情况下 通知用户控件。但我的问题是用户控件永远不会得到通知。我可以看到属性正确更新,但委托类型的事件始终为空。

这是我的委托类型

public delegate void Submited(bool value);

我有一个用户控件,它被添加到表单中,然后在单击按钮时加载该表单。 下面是我如何将用户控件添加到表单

UserDoc UserDocUserControl= new UserDoc(); //This is user control
UserDocForm UserDocWinForm = new UserDocForm(); //This is Form
UserDocWinForm.Controls.Add(UserDocUserControl);
UserDocWinForm.Show();

这是我的 UserDoc 用户控件

public partial class UserDoc : UserControl
{
    GetUserAction Var_GetUserAction = new GetUserAction();
    public UserDoc()
    {
        InitializeComponent();
        Var_GetUserAction.DocSubmitted += OnDocSubmitted;                         
    }

    private void OnDocSubmitted(bool value)
    {
       // it never get hits
       MessageBox.Show("Event Caught");
    }   
    /// More code which is not making any difference here.........

}

这是我的班级,正在密切关注房产

public class GetUserAction
{   
    public event Submited DocSubmitted;        
    private bool _IsAllowed
    public bool IsAllowed
    {
        get { return _IsAllowed; }
        set
        {
            // _IsAllowed gets hit when ever the value is changed
            if (_IsAllowed != value)
            {
                _IsAllowed = value;
                // this DocSubmitted is always Null
                if (DocSubmitted != null)
                {
                    //It never comes here?????
                    DocSubmitted(value);
                }
            }
        }
    }
    private void SetIsAllowed()
    {
        IsAllowed = // some other code is updating this part and its working fine;
    }
}

任何指导/帮助将不胜感激,我无法弄清楚我做错了什么!!!

【问题讨论】:

  • 您能否将其重构为一个控制台应用程序,我们可以运行它来查看错误?
  • @Enigmativity 它有服务正在运行并且需要主机 .. 如果简单的话我会做到的
  • 正在更新的GetUserAction 对象可能与UserDoc 类引用的对象不同。您可能的意思是将GetUserAction 作为UserDoc 构造函数中的引用传递。
  • @Angloos - 如果你很难重构你的代码,那可能意味着我们很难回答。
  • @Angloos - 看起来 Loathing 做了一个有根据的猜测。请注意,您提供的代码中没有任何内容表明这是问题。这就是只发布您认为相关的内容的问题。

标签: c# winforms events


【解决方案1】:

正在更新的GetUserAction 对象可能与UserDoc 类引用的对象不同。您可能的意思是将GetUserAction 作为UserDoc 构造函数中的引用传递。

【讨论】:

    【解决方案2】:

    你必须设置 IsAllowed 然后它调用事件

    添加:

        public UserDoc()
        {
            InitializeComponent();
            Var_GetUserAction.DocSubmitted += OnDocSubmitted;
            //set properties to call event
            Var_GetUserAction.IsAllowed = true;
        }
    

    你可以得到来源: https://drive.google.com/file/d/0B_JxRo8fyd3QbnBxVE5HdmF1bWs/view?usp=sharing

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-22
      • 2014-12-15
      相关资源
      最近更新 更多