Encapsulating a Windows.Forms.Button

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-04-23T19:29:49Z Indexed on 2010/04/23 19:33 UTC
Read the original article Hit count: 139

I want to define a special kind of button that only allows two possible labels: "ON" and "OFF". I decided to inherit from a Windows.Forms.Button to implement this but now I don't know I how should enforce this rule. Should I just override the Text property like this?

public override string Text
{
    set
    {
        throw new InvalidOperationException("Invalid operation on StartStopButton!");
    }
}

The problem I see with this is that I am breaking the contract that all buttons should have. If any code tries something like

foreach (Button button in myForm) {
    button.Text = "123";
}

they will get an Exception if I have any of my special buttons on the form, which is something that isn't expectable. First, because people think of properties just as "public" variables, not methods, second, because they are used to using and setting whatever they want to buttons without having to worry with Exceptions.

Should I instead just make the set property do nothing? That could also lead to awkward results:

myButton.Text = "abc";
MessageBox.Show(abc); //not "abc"!

The general idea from the OO world is to in this kind of cases use Composition instead of inheritance.

public class MySpecialButton : <Some class from System.Windows.Forms that already knows how to draw itself on forms>

    private Button button = new Button(); //I'd just draw this button on this class
                                          //and I'd then only show the fields I consider
                                          //relevant to the outside world.
    ...
}

But to make the Button "live" on a form it must inherit from some special class. I've looked on Control, but it seems to already have the Text property defined. I guess the ideal situation would be to inherit from some kind of class that wouldn't even have the Text property defined, but that'd have position, size, etc properties available. Upper in the hierarchy, after Control, we have Component, but that looks like a really raw class.

Any clue about how to achieve this? I know this was a long post :(

Thanks

© Stack Overflow or respective owner

Related posts about winforms

Related posts about object-oriented-design