I have been trying to build a user control with some custom properties set in the designer. However the control involves some interop code and settings which shouldn't be adjusted at runtime. Is there a way to stop the values being changed after they have been initially set by the designer code?
You could throw an exception inside the property setter?
public int SomeProperty {
set {
if(designerComplete) {
throw new IllegalOperationException();
}
}
}
Set designerComplete as a class variable - set it to true after the InitializeComponent method is called in the constructor.
Are you able to modify the property definition? One approach is, add a sentinel to the property setter, and allow only one set operation (which would usually be done by InitializeComponent()):
private int _myProperty;
private bool _isMyPropertySet = false;
public int MyProperty
{
set
{
if (!_isMyPropertySet)
{
_isMyPropertySet = true;
_myProperty = value;
}
else
{
throw new NotSupportedException();
}
}
}
The WinForms architecture provides a built-in way to test whether code is currently being executed in design mode - the Component.DesignMode property.
So you probably want an implementation something like this:
private int _foo;
public int Foo
{
get { return _foo; }
set
{
if (this.DesignMode)
throw new InvalidOperationException();
_foo = value;
}
}
Michael provided a great answer, and it will solve your problem at runtime. However, at design time, if you need to be able to change that value more than once (it is design time, and the probability is likely high), then you will want to combine the DesignMode check with Michaels example:
private int _myProperty;
private bool _isMyPropertySet = false;
public int MyProperty
{
set
{
if (this.DesignMode || !_isMyPropertySet)
{
_isMyPropertySet = true;
_myProperty = value;
}
else
{
throw new NotSupportedException();
}
}
}
Now you will be able to edit this value to your hearts content during design, without running into that NotSupportedException() and getting a botched designer on the second set.