2017-04-03 59 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'。如果您想覆蓋基類方法,那麼您的方法簽名必須與基類匹配。 –

相關問題