我正在将我的第一个 MVVM 项目放在一起。我有一个状态栏,它将从应用程序内的各种视图(用户控件)更新。每个视图都有自己的 DataContext。我最初的想法是创建一个 ViewModelBase 类,它实现了 INotifyPropertyChanged 接口,还包含一个公共属性来绑定我的 StatusBar 的文本。应用程序中的所有其他 ViewModel 都将继承 ViewModelBase 类。当然,这是行不通的。我怎样才能做到这一点?我没有使用 MVVM Light 或任何其他框架,而是在 vb.net 中编程。提前致谢。
更新 - 以下是 Garry 在第二个答案中提出的翻译,我仍然无法从 MainViewModel 修改状态文本?有人看到他的 c# 代码的 vb 翻译有问题吗?这种 MVVM 过渡导致大量脱发!
ViewModelBase.vb
Imports System.ComponentModel
Public Class ViewModelBase
Implements INotifyPropertyChanged
Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged
Protected Sub OnPropertyChanged(ByVal propertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub
End Class
状态视图模型.vb
Public Interface IStatusBarViewModel
Property StatusBarText() As String
End Interface
Public Class StatusBarViewModel
Inherits ViewModelBase
Implements IStatusBarViewModel
Private _statusBarText As String
Public Property StatusBarText As String Implements IStatusBarViewModel.StatusBarText
Get
Return _statusBarText
End Get
Set(value As String)
If value <> _statusBarText Then
_statusBarText = value
OnPropertyChanged("StatusBarText")
End If
End Set
End Property
End Class
主视图模型.vb
Public Class MainViewModel
Inherits ViewModelBase
Private ReadOnly _statusBarViewModel As IStatusBarViewModel
Public Sub New(statusBarViewModel As IStatusBarViewModel)
_statusBarViewModel = statusBarViewModel
_statusBarViewModel.StatusBarText = "Test"
End Sub
End Class
Status.xaml (用户控件)
<StatusBar DataContext="{Binding StatusViewModel}">
...
<w:StdTextBlock Text="{Binding StatusText, UpdateSourceTrigger=PropertyChanged}" />
应用程序.xaml.vb
Class Application
Protected Overrides Sub OnStartup(e As System.Windows.StartupEventArgs)
Dim iStatusBarViewModel As IStatusBarViewModel = New StatusBarViewModel()
Dim mainViewModel As New MainViewModel(iStatusBarViewModel)
Dim mainWindow As New MainWindow() With { _
.DataContext = mainViewModel _
}
mainWindow.Show()
End Sub
End Class
主窗口.xaml
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GlobalStatusBarTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<local:Status Grid.Row="1" />
</Grid>
</Window>