How can events be handled when the class is static?

85 views Asked by At

Suppose you have the following class

public class Message : Control, IDisposable {

    internal static class _Text : RichTextBox {

        protected override void OnLinkClicked( LinkClickedEventArgs e ) {
            System.Diagnostics.Process.Start(e.LinkText);
        }

        public _Text() {
            BorderStyle = System.Windows.Forms.BorderStyle.None;
            BackColor = Color.Orange;
            ForeColor = Color.White;
            ReadOnly = true;
            this.Font=new Font( "Segoe UI", 10 );
            Text="";
            Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top;
            ScrollBars = RichTextBoxScrollBars.None;
        }
    }

    public Message() {
        SetStyle( ControlStyles.AllPaintingInWmPaint|ControlStyles.OptimizedDoubleBuffer|ControlStyles.ResizeRedraw|ControlStyles.SupportsTransparentBackColor|ControlStyles.UserPaint, true );
        UpdateStyles();
        DoubleBuffered = true;
        _Text.ContentsResized+=_Text_ContentsResized;
        _Text.Location = new Point(15,5);
        _Text.Width = Width - 15;
        this.Controls.Add( _Text );
        _Text.Visible = true;
    }


    void _Text_ContentsResized( object sender, ContentsResizedEventArgs e ) {
        _Text.Height = e.NewRectangle.Height;
        base.Height = _Text.Height + 10;
    }

}

The problems being reported in the above code (as an example), are as follows :

_Text.ContentsResized+=_Text_ContentsResized; reports

An object reference is required for the non-static method

.... (etc)

this.Controls.Add( _Text ); reports

Message._Text is a type but is being used as a variable

and the contents of the event handler _Text_ContentsResized reports the same error as reported for the first error described here (as follows)

An object reference is required for the non-static method

.... (etc)

Keeping the conceptual idea behind this, I would like the inner control _Text to be a static and more natural element of the parent control Message but to still be able to access it's properties and events. For the properties, I could likely create a static wrapper for get/set, however I still have the issue of being unable to handle any events from that object.

So the question is -- how can I raise the event from a static object/class to a non-static caller without creating a latebound copy of the object (_Text t = new _Text())

0

There are 0 answers