简体   繁体   English

从WinForm调用对象事件

[英]Call object event from WinForm

I need to raise objects event in WinForm. 我需要在WinForm中引发对象事件。 Need to change control state (in UI) when object property has been changed. 更改对象属性后,需要更改控件状态(在UI中)。 How can I raise objects event in UI? 如何在UI中引发对象事件?

EDIT: On form i have 2 drop downs binded to object properties. 编辑:在表单上,​​我有2个下拉列表绑定到对象属性。 I need to disable second drop down when selection on first one is false. 当第一个选择错误时,我需要禁用第二个下拉菜单。

You can't raise object's event. 您不能引发对象的事件。 Only object can raise it's event. 只有对象可以引发事件。 You can only subscribe to object's event. 您只能订阅对象的事件。 Why? 为什么? Because event is actually a pair of methods for adding and removing handlers. 因为事件实际上是添加和删除处理程序的一对方法。 It's not same as property of delegate type, which you can invoke from any place. 它与可以在任何地方调用的委托类型的属性不同。

So, you should do something which will cause object to raise that event. 因此,您应该做一些会导致对象引发该事件的事情。 There is no way to raise event directly. 无法直接引发事件。


Here is sample of INotifyPropertyChanged usage: 这是INotifyPropertyChanged用法的示例:

// your object
public class Foo : INotifyPropertyChanged
{
    private bool _bar;

    public bool Bar
    {
        get { return _bar; }
        set { 
            if (_bar == value)
                return;

            _bar = value;
            OnPropertyChanged("Bar");
        }
    }

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

And bind your control to this object: 并将您的控件绑定到该对象:

yourControl.DataBindings.Add("Enabled", foo, "Bar");

When Bar property will be changed, foo object will raise event, and your control will handle that event. Bar属性将被更改时,foo对象将引发事件,而您的控件将处理该事件。

If you object already implements INotifyPropertyChanged , you can do the following inside your WinForm class: 如果您的对象已经实现INotifyPropertyChanged ,则可以在WinForm类中执行以下操作:

yourObject.PropertyChanged += (s, e) =>
    {
        if (e.PropertyName == "Name") {
            //Check the value of the property here, etc...
            button1.Enabled = false;
        }
    };

In that example, Name is the property you want to monitorize. 在该示例中,“ Name是您要监视的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM