.Net: Why we can't access to some properties of a control programmatically in winforms?
.Net: Why we can't access to some 开发者_开发问答properties of a control programmatically in winforms? For example, "Locked" property of a groupbox is not accessible via code. So What Possibly can I do when I want to locked it programmatically ? Using Enabled = False will greyed out all controls within it and this is not what I wanna to be.
Any Suggestions ?
Do you know what Locked really mean? This isn't a normal property and isn't affecting runtime anyhow, only designer. You probably should go to the problem you're trying to solve. I can assure you: the "Locked" property isn't needed for that.
Locked is not a property at all - it is just a value stored in the resource file. Locking the Form
control yields a boolean resource value $this.Locked
set to true.
Further some properties are attached to controls using IExtenderProvider
similar to attached properties in WPF. For example the designer will show a propery ToolTip
for all controls after adding a ToolTip
control to the designer. To set the tool tip text by code you have to use
this.toolTip1.SetToolTip(this.button1, "A button.");
because there is no ToolTip
property for controls.
And there are more mechanisms like ICustomTypeDescriptor
that cause different properties to be shown in the designer than the properties that are really defined for the control.
There is a generic solution to disable WinForms controls without graying them but unfortunately I can neither remember nor find it...
You could disable it!!!!
daveTextBox.Enabled = False
This will obviously change the look of the control. If you don't want to change the look of the control then override the key press event handler to do nothing.
As others have already pointed out, what you actually want to do is to make the controls readonly, but except for textboxes and radiobuttons this can be fairly complicated.
Below is an excerpt from some code I've written to handle something like this, but the client wanted cheap rather than perfect so I had some flexibility so it might not work for you. The method is just called by SetControlsReadonly(gb.Controls)
(assuming a groupbox called gb).
Private Sub SetControlsReadonly(ByVal ctrls As Windows.Forms.Control.ControlCollection)
For Each ctrl As Control In ctrls
ctrl.Enabled = True ' first enable everything so that it'll all look the same
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).ReadOnly = True
ElseIf TypeOf ctrl Is Button Then
CType(ctrl, Button).Enabled = False
ElseIf TypeOf ctrl Is CheckBox Then
CType(ctrl, CheckBox).AutoCheck = False
ElseIf TypeOf ctrl Is ComboBox Then
ctrl.Enabled = False
if ctrl.Tag IsNot Nothing Then
' call method that hides the combo and instead shows a readonly textbox in the same location containing the same data
End If
ElseIf TypeOf ctrl Is DateTimePicker Then
ctrl.Enabled = False
End If
SetControlsReadonly(ctrl.Controls)
Next
End Sub
精彩评论