views:

32

answers:

2

hi, I have a simple UserControl containing a ComboBox which is empty at first. The setter for that CB adds items to it and the getter returns the selected item. When adding this UC to a Form, the designer automatically calls the getter for the CB which is empty. The method to fill up the CB with items is called later. I can think of one or two ways to bypass this problem by "messing around" in the code. But before I start that I'd like to ask you if there is a way to stop the designer from calling the getter method. Maybe with a attribute similar to Browsable or Bindable? thx

+1  A: 

Try this:

public ListBoxItem MyProperty
{
    get
    {
        if (this.DesignMode)
        {
            return new ListBoxItem("empty");
        }
        else
        {
            return comboBox1.SelectedItems[0];
        }
    }
}

The getter will still be called, but you can control what is returned here.

Or, I think putting the [Browsable (false)] attribute above the getter might work, too, but I'm not sure.

MusiGenesis
I guess my code is just bad. I have an event that registers a change of the selected index of the CB. so the designer calls the getter, the event is raised and a method that accepts the selected item throws an exception (false type). Of course, i can check within the method if the presented item is of the right type. etc. But I would really like to know if one can simply hide getters from the designer or is this demand of mine also a bad idea?
LLEA
Sometimes getting controls to behave normally in the designer is difficult, but having combo boxes on a form is pretty normal, so I'm not sure exactly why you're getting this problem. A simple solution would be to only attach the change event to the combo box at runtime. In the load event, you can put something like `cb.onChange += new EventHandler ... `, instead of selecting that event in the designer and double-clicking it.
MusiGenesis
thx for your efforts. I could use the part with this.DesignMode. Besides that you are right. there are many ways to bypass that problem, but i was just curious ... and now I got an answer.
LLEA
+1  A: 

It is not that clear to me what this getter might look like. However, you want to make sure that the designer doesn't serialize properties that should only ever be used at runtime. Do this with an attribute:

    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    [Browsable(false)]
    public int SomeProperty { 
        //etc... 
    }
Hans Passant
thx...that's what I looked for. It works. the designer does not call the getter method anymore.
LLEA