为什么这段代码需要Shadows而不是Overrides?

时间:2017-04-03 20:56:06

标签: vb.net

我在下面的代码中遇到了各种困难,直到我引用了这个SO post并决定我必须需要Shadows,之后它才能正常工作;我只是不太了解它。引用的帖子似乎有很多关于“不喜欢使用Shadows”组的追随者,但我不知道下面的代码如何在没有Shadows的情况下编写,也不明白为什么最终需要它。

There was a XAML page that defines the buttons to invoke the annotation methods and also display the FlowDocumentReader
I didn't think that was necessary for this question but can add it if necessary

Imports System.IO
Imports System.Windows.Annotations
Imports System.Windows.Annotations.Storage

Partial Public Class MainWindow
  Inherits Window

  Private stream As Stream

  Public Sub New()
    InitializeComponent()
  End Sub

  Protected Shadows Sub OnInitialized(sender As Object, e As EventArgs)
    ' Enable and load annotations
    Dim service As AnnotationService = AnnotationService.GetService(reader6)
    If service Is Nothing Then
      stream = New FileStream("storage.xml", FileMode.OpenOrCreate)
      service = New AnnotationService(reader6)
      Dim store As AnnotationStore = New XmlStreamStore(stream)
      service.Enable(store)
    End If
  End Sub

  Protected Shadows Sub OnClosed(sender As Object, e As EventArgs)
    ' Disable and save annotations
    Dim service As AnnotationService = AnnotationService.GetService(reader6)
    If service IsNot Nothing AndAlso service.IsEnabled Then
      service.Store.Flush()
      service.Disable()
      stream.Close()
    End If
  End Sub

End Class

代码是为教程编写的,用于查看Flow Document中的Annotations。 XAML页面上的Window元素包含:

Initialized="OnInitialized" Closed="OnClosed" 

为什么需要Shadow而不是Overrides,这是否正确使用了Shadows?我以前使用Overrides没有问题,但不是在这里。看来引用帖子中的一些后来的评论可能与这种情况有关并且表明Shadows是可以的,但我想有针对性地提出这个问题。

1 个答案:

答案 0 :(得分:1)

OnInitializedOnClosedWindow类上的方法,它们的参数与您的参数不匹配(没有sender参数),因此您需要将它们声明为Shadows以使编译器满意。我认为您要做的是避免使用OnInitializedOnClosed作为事件处理程序名称,例如。

Protected Sub Window_Initialized(sender As Object, e As EventArgs)
'...
Protected Sub Window_Closed(sender As Object, e As EventArgs)

'Initialized="Window_Initialized" Closed="Window_Closed"