Interactive Design-Time User Control

2019-07-11 06:38发布

问题:

I apologise if the title was confusing, it took me nearly 5 minutes to finally think of a title for this one...

Okay, you know how in Visual Studio Express when you add a TabControl to the Form, and you can click on the right-arrow on the top right of the TabControl and it will add a new TabPage, or remove one?

Well, I'm creating a User Control where I need people to be able to switch between Panels (my user control is made up of several Panels). I know this is possible as I've used a Ribbon Control in the past and you could add new buttons etc in the Designer View.

Can somebody please provide any suggestions/advice on how I might go about acheiving this?

Thank you

回答1:

When you make a control that is inherited from Control, you have to make use of a couple of properties such as IsDesignMode, you can then construct event handlers especially for within Design Mode:

if (IsDesignMode){
   // Handle the interactivity in Design mode, such as changing a property on the
   // Properties toolbox
}

Suppose the control has an event such as MouseClick, you can do this:

private void control_MouseClick(object sender, MouseEventArgs e){
   if (IsDesignMode){
       // Do something here depending on the Click event within the Designer
   }else{
       // This is at run-time...
   }
}

Another I can think of is 'ShouldSerialize' followed by a publicly accessible property in order to persist the property to the designer-generated code, suppose for example a Control has a boolean property Foo

public bool Foo{
    get{ return this._foo; }
    set{ if (this._foo != value){ 
                this._foo = value; 
         }
       }
}

public bool ShouldSerializeFoo(){
    return true; // The property will be persisted in the designer-generated code
                 // Check in Form.Designer.cs...
}

If ShouldSerializeFoo returned false, no property is persisted, its the opposite when true, it will be buried within the Form.Designer.cs code...

Hope this helps, Best regards, Tom.



回答2:

If I understand your question correctly, you're talking about smart tags.

The process is a little bit involved, so I'm not going to try to post a complete sample. Instead, I'll refer you to this tutorial on the subject. To make a long story short, you have to create a custom designer, and register one or more custom actions. You can use this to create a combo box listing the available panels and switch between them when the selected item is changed.

(Note - the term "smart tags" has two distinct meanings in Visual Studio - I'm specifically talking about the visual designer smart tags, not smart tags in the code editor).