问题
I am making a user control in MS Visual C#, and there is one thing that I just can't find an answer to:
How do I limit which dimensions a control can be resized in during design view?
For a clear example of what I'm asking, the built in TrackBar control can only only be made wider, not taller, and only displays the resizing squares on the left and right in design mode. Is there a way to replicate this for a user control?
I have tried setting MinimumSize and MaximumSize values in the designer for my control, but this doesn't give ideal results.
回答1:
To get the full behavior you're talking about (no adorners on top/bottom or left/right) and custom functionality inside the design time environment, you'll probably have to resort to building a custom control designer for your control.
This is a huge topic, as there are a lot of things you can do. Effectively what you'd do is create a class that inherits from ControlDesigner
, override whatever functionality you need, then register it on your user control with the DesignerAttribute
, specifying typeof(IDesigner)
for the 2nd parameter (and your custom ControlDesigner-derived type for the first).
Enhancing Design-time Support
Custom Designers
ControlDesigner class example
Custom Design-time Control Features in Visual Studio .NET
Now, in the case of TrackBar, it has its own designer that overrides the ControlDesigner.SelectionRules property. This property simply lets you return an enumeration value (it's a Flags enum, so you can OR them together) indicating how your design-time selection adorners appear (or not appear). Once you've restricted design-time resizing via a designer, it's simply up to your control itself to constrain its own size vai SetBoundsCore.
回答2:
I'm fairly sure you can do this with Control.SetBoundsCore
, as described here.link text
回答3:
I am not sure for the resizing square but MaximunSize and MinimumSize are the right values for you. But it's not enough to set them in the constructor of your class because everytime you drop an instance of your control from the designer to a form these values get set after the constructor.
You should:
override MinumumSize and MaximumSize, and do net set the base value from your value but your value.
private Size maxSize = new Size(100, 5);
public override Size MaximumSize
{
get { return base.MaximumSize; }
set { base.MaximumSize = maxSize; }
}
create a public method in your class:
public bool ShouldSerializeMaximumSize()
{
return false;
}
and
private void ResetMaximumSize()
{
me.MaximumSize = maxSize;
}
These methods are a convention from the Windows Forms Desinger: http://msdn.microsoft.com/en-us/library/53b8022e.aspx
来源:https://stackoverflow.com/questions/3093550/limit-resizable-dimensions-of-a-custom-control-c-net