【问题标题】:Windows Form User Control Does Not Update When Its Property is UpdatedWindows 窗体用户控件在其属性更新时不更新
【发布时间】:2013-03-25 09:33:56
【问题描述】:

我在 Visual Basic 窗体应用程序中创建了一个用户控件。它有一个名为 ID 的属性

Private intID As Integer

Public Property ID() As Integer
    Get
        Return intID
    End Get
    Set(value As Integer)
        intID = value
    End Set
End Property

并且在用户控件的加载方法中,我正在根据 ID 刷新用户控件中的组件。

Private Sub UserControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    UpdateUserControlFields() ' This Method uses ID within
End Sub

现在,当我在添加了此用户控件的表单中执行某些操作时,我希望此控件显示为正确的 ID。例如,我有一个DataGridView,并且只要选择更改,我想更新用户控制:

Private Sub MyDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles MyDataGridView.SelectionChanged
    If Not IsNothing(MyBindingSource.Current) Then
        UserControlONE.ID = MyBindingSource.Current("someID")
        UserControlONE.Refresh() ' Doesn't Work.
        UserControlONE.Update() ' Doesn't Work.
    End If
End Sub

问题是用户控件仅在第一次使用所选 ID 时正确加载,我似乎无法重新加载它的数据。这意味着如果属性 ID 的值发生更改,我不知道如何强制重新加载用户控件。它显示与加载的第一个 ID 相同的数据。任何帮助将不胜感激。

【问题讨论】:

  • 您确定ID被多次更改。在此行设置断点UserControlONE.ID = MyBindingSource.Current("someID") 并检查每次在网格中选择某些内容时它是否会中断
  • 是的,它每次都会中断并且 ID 设置正确。没有发生的是,即使用户控件的 ID 已更新,用户控件也不会再转到其加载方法。用户控件的加载方法只在第一次调用。
  • 如果调用 ResetBindings 方法是否会更新 导致绑定到 BindingSource 的控件重新读取列表中的所有项目并刷新其显示值。
  • ResetBindings 不是为我做的。

标签: vb.net properties user-controls form-load


【解决方案1】:

不要在控件加载事件中更新ID,而是在属性变化时更新:

Private intID As Integer

Public Property ID() As Integer
    Get
        Return intID
    End Get
    Set(value As Integer)
        intID = value
        UpdateUserControlFields() ' This Method uses ID within
    End Set
End Property

UserControl_Load event“在控件第一次可见之前发生。”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    相关资源
    最近更新 更多