我是VB.net的新手所以请理解。我有MainWindow, Frame1, Frame2 (AdFrame1), Page1.
MainWindow
在启动时从Page1
加载Frame1
。在MainWindow.vb class
我有一个Public Sub使Frame2
可见。
我如何分享Public Sub,以便我可以使用Page_Mouseup Event来显示Frame2(AdFrame1)
我尝试了Public Shared Sub,但是我收到了这样的错误:“无法在没有类的显式实例的共享方法或共享成员初始化程序中引用类的实例成员”
MainWindow.vb中的代码:
Private Sub MainWindow2_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Me.MouseUp
AdClick()
End Sub
Public Sub AdClick()
Try
clicks += 1
If clicks >= 10 Then
'After 5 seconds Adframe CloseLink and TextBlock1 will hide.
AdFrame1.Visibility = Windows.Visibility.Visible
CloseMainButton.Visibility = Windows.Visibility.Visible
InitializeComponent()
dpTimer = New DispatcherTimer
dpTimer.Interval = TimeSpan.FromMilliseconds(10000)
AddHandler dpTimer.Tick, AddressOf TickMe
dpTimer.Start()
clicks = 0
End If
Catch ex As Exception
MessageBox.Show("Oops! Error X0123A1. Please contact us with error ASAP!", "Error!", MessageBoxButton.OK)
End Try
End Sub
'After 10 sesonds auto close
Private Sub TickMe()
AdFrame1.Visibility = Windows.Visibility.Hidden
End Sub
Code Page1.vb
Private Sub Page1_MouseUp(ByVal sender As Object, ByVal e As MouseEventArgs) Handles Me.MouseUp
AdClick() (inaccessible due to protection)
End Sub
那么如何与Page1
分享AdClick()答案 0 :(得分:3)
首先,请注意Shared
关键字与可见性无关 - 例如,成员可以是Public Shared
或Private Shared
。 Shared
成员与C#中的static
成员相同 - 它对所有类的实例都是通用的(请参阅:What is the use of a shared variable in VB.NET?)
对于实际问题,我建议只是挂钩已经存在的事件:
Class MainWindow2
Private WithEvents _Page1 as New Page1
Private Sub MainWindow2_MouseUp(sender As Object, e As MouseEventArgs) _
Handles Me.MouseUp, _Page1.MouseUp
AdClick()
End Sub
Private Sub AdClick()
'Do something
End Sub
End Class
公开方法通常是错误的方法 - 如果你希望MainWindow
做某事,那么它自己负责这样做会好得多,而不是让其他一些类试图在其他地方做这件事。对于活动,Page1
仅负责让MainWindow
知道它已被点击;这使得MainWindow
决定如何处理它,Page1
需要对MainWindow
中包含的方法一无所知。
如果您在Page1
上有一个按钮,您甚至可以添加自定义事件,例如:
Class Page1
'make your own event
Public Event Button1Click(sender As Object, e As RoutedEventArgs)
Private Sub Button1_Click(sender As Object, e As RoutedEventArgs) _
Handles Button1.Click
RaiseEvent Button1Click(sender, e)
End Sub
End Class
然后在MainWindow
:
Private Sub ClickHandle(sender As Object, e As RoutedEventArgs) _
Handles _Page1.Button1Click
AdClick()
End Sub
这会让页面内的按钮单击传播到主窗口。
如果您的网页是在运行时创建的,则无法使用WithEvents
和Handles
,但您可以这样做:
Dim newPage as New Page1
AddHandler newPage.MouseUp, AddressOf MainWindow2_MouseUp
确保在页面超出范围之前删除处理程序(处理程序保留强引用,以便newPage
永远不会使用仍附加的处理程序收集垃圾! - >内存泄漏)。
RemoveHandler newPage.MouseUp, AddressOf MainWindow2_MouseUp