首页 > 解决方案 > 我应该如何使用接口将应用程序的核心连接到 UI?

问题描述

我正在用 VB.NET 编写一个应用程序,其中在 Core 类中执行各种计算。它们由 MainWindow 类 (UI) 中的用户输入调用。计算完成后,它们会再次显示在主窗口中。

试图避免意大利面条式代码并意外地使 Core 依赖于 UI,我的理解是我应该使用接口。我想我了解接口是如何工作的,但我不确定如何正确实现它以实现核心和 UI 之间的双向通信。

下面是一个非常简单的例子。

核心类:

Public Module Core
    Public UI As UIinterface
        
    Sub Init()
        UI = New MainWindow
    End Sub
        
    Sub RunCalculations()
        Dim calculationResult As String = 5 + 5         
        UI.DisplayResults(calculationResult)
    End Sub

End Module

UIInterface接口:

Public Interface UIInterface
    Sub DisplayResults(results as String)
End Interface

还有我的 MainWindow 类:

Class MainWindow
    Implements UIInterface
    
    Private Sub DisplayResults(results as String) Implements UIInterface.DisplayResults
        label1.text = results
    End Sub
    
    Private Sub RunButton_Click(sender As Object, e As RoutedEventArgs)
        Core.RunCalculations() 'This is probably wrong
    End Sub 
End Class

如您所见,我不知道如何将按钮单击传递给核心。据我了解,这应该以某种方式通过 UIInterface 完成,但我无法弄清楚,而且我似乎无法在任何地方找到任何相关示例。我在接口使用中发现的只是单向通信。

有人可以建议吗?如果我对Interfaces 的理解有缺陷?如果是这样,将 Core 与 UI 尽可能分开的正确实现是什么,以便以后在不更改 Core 中的任何内容的情况下轻松切换到另一个 UI 实现?

编辑:我正在为我的 UI 使用 WPF。

标签: vb.netuser-interfaceinterface

解决方案


这是基于您提供的代码的简化 WPF 示例。

<!-- Details elided, but if you add a new window in a WPF project,
you'll start out with what you need -->
<Window x:Class="MainWindow"
        Title="MainWindow">
    <Grid>
        <Button Content="Run Calculations" Command="{Binding RunCalculationsCommand}" />
        <TextBlock Text="{Binding Results}" />
    </Grid>
</Window>
Public Class Model
    Implements INotifyPropertyChanged

    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
    'In C#, this can be made into an extension, but I don't think 
    'the VB event model gives us granular enough access to do this.
    Private Sub RaisePropertyChanged(<CallerMemberName> Optional ByVal propertyName As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    'Boilerplate nature of visible properties can be annoying; I don't
    'have any suggested workarounds beyond generated code.
    Private _Results As String
    Public Property Results As String
        Get
            Return _Results
        End Get
        Set(value As String)
            _Results = value
            RaisePropertyChanged()
        End Set
    End Property

    'ActionCommand implementation left as an exercise for the reader.
    Public ReadOnly Property RunCalculationsCommand As ICommand = 
        New ActionCommand(AddressOf RunCalculations)

    Public Sub RunCalculations()
        Dim calculationResult As String = (5 + 5).ToString()
        Results = calculationResult
    End Sub
End Class

这需要的最后一件事是将 的 设置DataContextMainWindow的实例的代码Model。对于此示例,在构造函数中分配一个新实例可能是最直接的(尝试在主窗口 ctor 上放置一个参数,我认为会导致框架出现问题)。


推荐阅读