Does Visual Inheritance work with User controls in

2019-08-12 09:01发布

问题:

I have a base User Control. I place Ok and Cancel buttons on the bottom right of the control and anchor them Bottom and Right.

I then create another user control that inherits from the base user control. I resize the inherited control (e.g. increase height or width). Throw the inherited control onto the form. Run. The inherited control does not honor the anchor properties of the Ok and Cancel buttons.

Here are the exact steps to repro.

1 - Create a new winforms project

2 - Create a base control (BaseControl1) with a Ok and Cancel buttons located at bottom/right. Anchor them there at Bottom,Right. Compile the app.

3 - Create a new User Control (UserControl1) that inherits from the base control (BaseControl1), created in step 1.

4 - Increase (in the designer) UserControl1's height or width.

5 - Throw UserControl1 onto Form1. Run. You'll see that Ok and Cancel buttons are not where they are supposed to be.

Am I doing something wrong, or does VS2008 simply not honor the anchor properties of the controls on the base user control?

回答1:

Change the Modifiers property on your buttons to Protected. Then, after you complete step 4, you'll notice the designer code for UserControl1 now contains a line of code to set the buttons' locations. That wasn't happening when your buttons were scoped as Friend.

I've always wondered why controls dropped from the toolbox weren't scoped to Private by default.



回答2:

I think your problem is that the default values for the Anchor property is not to be anchored. When you change the property and compile, that doesn't mean that's the default setting for classes that inherit your control.

If you are using the property selector, Visual Studio automatically puts some code in your application to change those values (i.e the designer code). Find the InitializeComponent() method and I bet you'll see something to the effect of:

this.myOKButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
this.myCancelButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

You'll need to set this property somewhere in your class, like the constructor, or override that property and specify the way you want it anchored.