【问题标题】:Prevent developer from placing a UserControl more than one time in Design Time防止开发人员在设计时多次放置 UserControl
【发布时间】:2018-04-16 07:47:51
【问题描述】:

我正在开发一个UserControl,我正在寻找一种方法来防止开发人员将这个UserControl多次放置到一个表单中。所有这一切都在设计时间。换句话说,我如何检测我的UserControl 是否已经放置ParentForm,在设计时间(!! !),并且阻止 第二个位置(如果那里已经有一个)?

我尝试了类似下面的示例...首先我不确定这是否是“正确”的方式,其次我找不到如何删除或停止放置 UserControl 以防万一已经有一个.

再一次,所有这一切,在设计时间!!!

Private Sub MyUserControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
    Dim _Count As Integer
    Dim _UserControl As MyUserControl
    For Each _UserControl In Me.ParentForm.Controls
        If _UserControl.Name.Contains("MyUserControl") Then
            _Count += 1
        End If
    Next
    If _Count > 1 Then
        MsgBox("Control have been placed.")
    Else
        MsgBox("Control haven't placed yet.")
    End If
End Sub

【问题讨论】:

  • 使用您使用的技术添加标签(winforms?)
  • 问答方式是在你的Load事件处理器中抛出异常。消息框不会赢得任何奖品,但您肯定会阻止添加第二个控件。非 Q 方式是创建自己的设计师。
  • @IvanH:是的 winforms!
  • Hmya,这是我不想回答的问题,您要派生的设计器类是内部的。使用好的反编译器并查看 System.Design.dll 中的 UserControlDocumentDesigner 类。复制/粘贴其代码。它已经接近你想要的了,它的 CanDropComponents() 方法现在可以防止 MainMenu 被删除。
  • 设置Site 属性后,您可以访问所需的一切。我已经向您展示了这项技术before。您可以遍历 host.Container.Components 集合以确定是否存在先前的实例。如果存在先前的实例,请使用`host.DestroyComponent(Me)` 删除新实例。

标签: vb.net winforms user-controls visual-studio-2017


【解决方案1】:

因为这个相同的表单很容易使用 new 和 dispose,它不适用于 beat weans 表单。仅在此相同。您可以使用互斥锁或此模块属性的某些单例实例或其他通知方法,该方法已创建以及何时释放。

    Sub New()
    '  This call is required by the designer.
    InitializeComponent()

    If Not co Is Nothing Then Throw New Exception
    co = Me ' assign public propert in  module or singleton

    ' Add any initialization after the InitializeComponent() call.

End Sub
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
    Try
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
    Finally
        co = Nothing
        MyBase.Dispose(disposing)
    End Try
End Sub
Module common
Property co As UserControl1

结束模块

【讨论】:

    【解决方案2】:

    我终于到此结束了……

    Private Sub Me_ParentChanged(sender As Object, e As EventArgs) Handles Me.ParentChanged
    
        Dim _ParentForm = DirectCast(Me.FindForm, Control)
        Dim _ControlName As String
    
        If _ParentForm IsNot Nothing Then
            For Each _Control As Control In _ParentForm.Controls
                If TypeOf _Control Is MyUserControl AndAlso _Control IsNot Me Then
                    Throw New ArgumentOutOfRangeException("", "You can place only one " & _ControlName & " control per form.")
                End If
                _Control = _ParentForm.GetNextControl(_Control, True)
            Next
        End If
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多