使用 Pedros 示例,以及我之前在我的应用程序中实现的其他服务,我在 vb.net 中组合了以下解决方案:
创建一个IFocus接口,这个接口可以通过焦点服务或者一个Mock来实现
Public Interface IFocusInterface
Sub Focus()
End Interface
创建一个 IFocusable 接口。这将由 ViewModel 实现并接受一个实现 IFocusInterface 的对象。
Public Interface IFocusable
Property FocusService As IFocusInterface
End Interface
使用单例模式实现焦点接口
Imports Microsoft.Phone.Controls
Public NotInheritable Class FocusService
Implements IFocusInterface
Private Sub New()
End Sub
Private Shared ReadOnly m_instance As New FocusService
Public Shared ReadOnly Property Instance() As FocusService
Get
Return m_instance
End Get
End Property
Public Sub Focus() Implements IFocusInterface.Focus
Dim rootFrame = TryCast(Application.Current.RootVisual, PhoneApplicationFrame)
If Not rootFrame Is Nothing Then
Dim page = TryCast(rootFrame.Content, PhoneApplicationPage)
If Not page Is Nothing Then
page.Focus()
Else
Throw New Exception("Unable to Cast the Root Frame Content into an Application Page")
End If
Else
Throw New Exception("Unable to Cast the RootVisual into a PhoneApplicationFrame")
End If
End Sub
End Class
在您的 ViewModel 中实现 IFocusable,并确保在构建 ViewModel 后将 Focus Service Singleton 传入 ViewModel。
Public Class MyViewModel
Implements INotifyPropertyChanged
Implements IFocusable
' Property for the Focus Service
<Xml.Serialization.XmlIgnore()> Public Property FocusService As IFocusInterface Implements IFocusable.FocusService
Public Sub Focus()
If Not FocusService Is Nothing Then
FocusService.Focus()
Else
Throw New Exception("ViewModel hasn't been passed a Focus Service")
End If
End Sub
End Class
Dim tMyViewModel as New MyViewModel
tMyViewModel.FocusService = Vacation_Calc_Model.FocusService.Instance