2017-04-03 60 views
0

我有困难的所有方式与下面的代码,直到我引用这个SO post并决定我必须需要阴影,在这之后的工作就好了;我只是不太明白这一点。引用的帖子似乎有很多信徒对'不喜欢使用阴影'组,但我不明白如何在没有阴影的情况下编写下面的代码,我也不明白为什么最终需要它。为什么此代码需要阴影而不是覆盖?

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 

该代码是为教程编写的,以查看使用流文档操作的注释。 XAML页面上的Window元素有:

Initialized="OnInitialized" Closed="OnClosed" 

为什么需要Shadow而不是Overrides,这是否正确使用了Shadows?我之前使用Overrides没有问题,但没有在这里。这篇文章后面的一些评论看起来似乎与这种情况有关,并指出Shadows是可以的,但我想指出这个问题。

+0

这是因为基类方法不可用,因此您为什么需要使用'shadows' ......使用'shadows'保留和/或维护方法'OnClosed'的定义;原因是如果基类方法已被更改。 – Codexer

回答

1

OnInitializedOnClosed都在Window类的方法,以及它们的参数不匹配你有什么(有没有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" 
+0

所以要确认,你说只需选择不同的方法名称,因为XAML Window元素'初始化=“”'并不真正关心什么方法命名,因为这方法会被调用时,Window元素被初始化不管什么。 “Closed =”“'也是如此,我碰巧选择了错误的方法名称,因为我太紧密地跟踪了本书教程。 – Alan

+1

是的,你可以为你的事件处理程序使用任何方法名称,但是你想避免基类中存在的方法,这样你就不会遇到这样的事情。 – Mark

+0

@Alan - 问题是你正在继承基类'Window'。如果您想覆盖基类方法,那么您的方法签名必须与基类匹配。 –

相关问题