如何处理userControl属性的事件?

时间:2014-04-15 04:07:29

标签: c# winforms user-controls

我有一个userControl的属性,如下所示:

    public enum Mode { Full, Simple }
    public Mode NavigatorMode { get; set; }

现在,当用户将属性(NavigatorMode)从完全模式更改为简单模式或反向时,我需要编写一个事件

我该怎么做?

2 个答案:

答案 0 :(得分:1)

将INotifyPropertyChanged实施到您的班级:

public class YourClass : INotifyPropertyChanged
{
    // Your private variable
    private Mode mode;

    // Declare the event 
    public event PropertyChangedEventHandler PropertyChanged;

    public YourClass()
    {
    }

    public Mode NavigatorMode 
    {
       get { return mode; }
       set
       {
          mode = value;

          // Call OnPropertyChanged whenever the property is updated
          OnPropertyChanged(mode);
       }
    }

    // Create the OnPropertyChanged method to raise the event 
    protected void OnPropertyChanged(Mode modeParam)
    {
       PropertyChangedEventHandler handler = PropertyChanged;
       if (handler != null)
       {
          handler(this, new PropertyChangedEventArgs(modeParam));
       }
    }
 }

答案 1 :(得分:0)

如何在控件中实现INotifyPropertyChanged接口?

或者只是编写自定义事件:

public event EventHandler<Mode> ModeChanged;

public Mode NavigatorMode
{
    get { return _navigatorMode; }
    set 
    {
        _navigatorMode = value;
        if(ModeChanged != null)
            ModeChanged(this, _navigatorMode);
    }
}

在用户控件之外,您可以处理该事件并根据模式执行某些操作。