我在Visual Studio Express 2013中的WinForms項目中添加了一個表單,我想將其用作其他表單的基本表單。假設我在此表單上放置了一個按鈕,並且我想擁有一個使此按鈕可見或不可見的屬性。未被設計人員保存的基類的屬性值
Imports System.ComponentModel
Public Class MyForm
<DesignerSerializationVisibility(DesignerSerializationVisibility.Content)>
Public Property ButtonVisible As Boolean
Get
Return Button1.Visible
End Get
Set(value As Boolean)
Button1.Visible = value
End Set
End Property
End Class
此文件設計器並沒有改變。我只是將一個按鈕添加到新窗體中。
當我現在創建一個繼承此類的新窗體時,我可以更改此屬性的值,並且在設計時該按鈕確實變爲可見或不可見。但是,當我編譯項目時,屬性被重置爲默認值。當我檢查我看到的派生形式的設計器文件時,更改後的屬性值不會添加到它,因此消失在空氣中。 當我手動將ButtonVisible = False
添加到設計器文件中時,它會工作並保持在那裏,所以我猜問題在於設計器不會將該行添加到設計器文件中。
這是派生形式的設計文件,之後我在設計更改的屬性值:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form2
Inherits MyForm
'Das Formular überschreibt den Löschvorgang, um die Komponentenliste zu bereinigen.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Wird vom Windows Form-Designer benötigt.
Private components As System.ComponentModel.IContainer
'Hinweis: Die folgende Prozedur ist für den Windows Form-Designer erforderlich.
'Das Bearbeiten ist mit dem Windows Form-Designer möglich.
'Das Bearbeiten mit dem Code-Editor ist nicht möglich.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.SuspendLayout()
'
'Form2
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(284, 261)
Me.Name = "Form2"
Me.Text = "Form2"
Me.ResumeLayout(False)
End Sub
End Class
正如你可以在上面的代碼中看到的,我已經嘗試來解決問題測試DesignerSerializationVisible
的不同值,但它們似乎沒有效果。
有什麼我忽略了嗎?我應該如何添加更改底層基類中的控件的屬性?
C#或VB.NET的答案都非常讚賞,無論你最喜歡什麼。
你是正確的,我做到了工作方式。作爲一個補充,在這種情況下需要在構造函數中用'True'初始化_ButtonVisibility變量。否則,它將默認爲false,而Button的可見性默認爲true,這又會讓事情變得糟糕。當一個屬性有其默認值時,它不會明確地添加到設計器代碼中。這會導致該按鈕再次出現,即使您將其設置爲false。很奇怪。 – Jens 2014-10-12 16:09:56
@Jens你說得對,我確認但不解釋這種行爲。我用我測試過的代碼編輯了我的答案,並且可以工作(聲明'_buttonVisibility時缺少'= True') – Chris 2014-10-12 16:27:18
非常好,謝謝! – Jens 2014-10-12 17:07:43