Sunday, March 6, 2011

Events in UserControl

Hi all, I am new to UserControls, and while developing my own control I found a problem with showing events of my control in the property grid at design time. If I have some events in my control I want to see them in Property grid and if I double-click that I want to have a handler, in the same way Microsoft does for its controls.

From stackoverflow
  • They should automatically appear if I'm not mistaken. Make sure you've built your project though, or changes won't propagate to open designers. And make sure it's a public event too. (Private/protected events rightfully shouldn't show up because they're not accessible.)

    One thing you can do to make your user's design experience nicer is to do something like the following:

        [Description("This event is raised when the user presses the enter key while the control has focus."),
        Category("Key")]
        public event EventHandler EnterPressed;
    

    The "description" bit puts a nice message in the description panel of the property window. The "category" bit puts it in a certain category (the default is Misc. at the end).

    By the way, you haven't specified a language or environment, so the above may need to be modified if it's not C# in Visual Studio 2005+.

  • I usually use this pattern, to create a custom event in UserControls:

        #region MyEvent CUSTOM EVENT
    
        protected virtual void OnMyEvent(MyEventEventArgs e)
        {
            if (MyEvent != null)
                MyEvent(this, e);
        }
    
        public delegate void MyEventHandler(object sender, MyEventEventArgs e);
        public event MyEventHandler MyEvent;
    
        public class MyEventEventArgs : EventArgs
        {
    
        }
    
        #endregion MyEvent CUSTOM EVENT
    

    This has the same naming convention of Microsoft events, you can fire OnMyEvent from inside your control, have custom EventArgs, handle MyEvent from other controls.

0 comments:

Post a Comment