Situation: I am making a Collapsible Panel. In my business situation, I am required to have the panel support the following:
A "direction" (ie, will it dock top, bottom, left, or right). This changes which direction it collapses and a few other things.
A "style". There are some predefined visual styles for this product (defining background color, gradient or not, text color, hover color, etc).
Here's the problem: certain styles are incompatible with certain directions. Here are the requirements:
There needs to be some way to prevent/w开发者_如何学JAVAarn the programmer if he/she coded the panel to have incompatible style and direction. For example, having the panel throw a runtime exception if they are incompatible will satisfy this requirement.
Not allow anyone to dynamically change either style or direction during runtime. If I need to, then I can allow it to be "dynamically" changed in
InitializeComponent
, but not anywhere else.The panel needs to be visible in Design View. but not necessarily able to be dragged and dropped in design view, and technically I don't need to even alter the attributes of the panel in design view. Though I obviously want either of those other things if possible.
One potential solution: Have the constructor take two inputs: a direction and a style. That way both the changes are treated as an atomic action. If they are not both changed at the same time, then between changing the direction/style and then changing the other, the panel will be in an inconsistent state. I want to avoid that.
How can I get the Design View to not use the default constructor and/or what are better practices for fulfilling the requirements?
Note
The Panel is only an example and a use case to ask the broader question. I want this post to answer the direct question on the best practices for getting the Design View to handle my requirements. If the Visual Studio supports injecting a non-default constructor in InitializeComponent
, then I want to know how (and any caveats with that). If there are better practices which fulfill the listed requirements, then I would like to know that as well.
Add support for the ISupportInitialize
interface which the designer can use to set all the properties and tell you when it's finsihed.
Partial answer: you can't make Designer use some custom constructor. You will need to put the logic in property setters.
Throwing exceptions there might lead to messy Designer errors. How about resetting fields to some proper state instead?
You will probably need to differentiate the behavior depending if you're in DesignMode
. If you haven't already, take a look at DesignMode considerations.
精彩评论