我有两个这样的课程:
Public Class Class1 : Inherits Control
Public Items As New List(Of Class2)
End Class
Public Class Class2
Private txt as String
Public Property Text As String
Get
Return txt
End Get
Set(ByVal value As String)
txt = value
End Set
End Property
End Class
当Class2的Text属性发生变化时,我想调用Class1的Invalidate()方法。
答案 0 :(得分:0)
代表可能是一个解决方案:
public class Class1 : Control
{
List<Class2> items = new List<Class2>();
public void Method1()
{
Action invalidate = delegate() { this.Invalidate(); };
items.Add(new Class2(invalidate));
items[0].Text = Guid.NewGuid().ToString(); //At this line call invalidate of class1
}
}
public class Class2
{
private string _text;
private Action _class1_invalidate;
public Class2(Action c1_invalidate)
{
this._class1_invalidate = c1_invalidate;
}
public string Text
{
get { return _text; }
set
{
_text = value;
this._class1_invalidate();
}
}
}
答案 1 :(得分:0)
您可以做的是编辑 class2 ,以便在更改txt属性时引发事件。该课程现在应该阅读
Public Class Class2
Private txt As String
Public Shared Event txtChanged()
Public Property Text As String
Get
Return txt
End Get
Set(ByVal value As String)
Dim oldTxt As String = txt
txt = value
If oldTxt = txt Then
Exit Property
Else
RaiseEvent txtChanged()
End If
End Set
End Property
End Class
注意第3行声明共享事件以及属性设置器中引发事件的行。共享事件是为了我们可以为 class2
的所有后续实例添加公共事件处理程序编写您的事件处理程序。
Private Sub Class2_txtChanged()
'add your code here to calle the invalidate method for class1
End Sub
最后,在Form的load事件中添加此行以将类链接到事件处理程序:
AddHandler Class2.txtChanged, AddressOf Class2_txtChanged
在您的事件处理程序中,您现在可以在 class1
的实例中调用 .Invalidate 方法