5

I'm working with MVVM and instead of reinventing the wheel, I thought I could find an open source view model base class. I can't find one.

1
  • What are you looking to have in this base class? Aug 5, 2010 at 13:51

7 Answers 7

6

MVVM Light is also a good solution, and it has a really easy to find base class :-)

1
  • 1
    I really, really wish I knew of that one before I put my suggestion forward ;-)
    – heads5150
    Aug 6, 2010 at 14:09
4

I would suggest that the basic principles of MVVM are so simple that it would be easier to reinvent the wheel. All the basic functionality you need is for the class to implement INotifyPropertyChanged (the base class could have the standard-style implementation of OnPropertyChanged(string propertyName)). Beyond that there's the RelayCommand or similar - just an ICommand implementation that executes a delegate in Execute.

All-in-all, just a few lines of code, and it keeps it very neat. What other functionality are you looking for? If it's to deal with the underlying BDO (say a DataRow, XmlNode or POCO) then it shouldn't really be in the VM base class, but a derived class.

Hope that helps.

1

The WPF Application Framework (WAF) is open source and contains a ViewModel base class (for implementing the Model-View-ViewModel pattern).

0

Microsoft Prism. Full access to the source code. A bit of a steep learning curve but once you get a handle of it, it works really well.

6
  • The steep learning curve flattens out if you have a good knowledge of OO and design patterns, and if you've worked with dependency injection before. Aug 5, 2010 at 13:57
  • Does Prism actually have a ViewModel base class? I've been using Prism on a few projects, and I never actually came across that....
    – BFree
    Aug 5, 2010 at 14:09
  • Same question: how do I access the base ViewModel in Prism? Which assembly/namespace is it in?
    – user134363
    Aug 5, 2010 at 16:07
  • prism isnt an MVVM framework.
    – ecathell
    Aug 6, 2010 at 13:04
  • 2
    For anyone reading this now, Prism does have a view model base class called NotificationObject, it has only basic functionality (i.e. property change notification) but that's all you really need to get started.
    – Lukazoid
    Mar 6, 2012 at 13:24
0

Check out Nikhail Kothari's blog for his SilverlightFX library, its an open source MVVM u might find useful.

0

SoapBox Core is an open source (LGPL) MVVM (and MEF) framework for building extensible MVVM applications. The class hierarchy includes a base ViewModel class (and interface for that matter).

-3

Here is an example of mine...it wont really help you, because want I want my viewmodels to do will be different then what you want your viewmodels to do...but maybe it will give you a start. And the thing with the base class is if you stick it in your Core...you only have to write it once...

Imports System.ComponentModel
Imports System.Windows
Imports Microsoft.Practices.Composite.Events
Imports WavelengthIS.Core.Services
Imports WavelengthIS.Core.Bases
Imports Ocean.OceanFramework.CommonDialog
Imports WavelengthIS.WPF.Events

Namespace WavelengthIS.WPF.Bases

    Public MustInherit Class ViewModelBase
        Inherits WavelengthIS.Core.Bases.Base
        Implements IDisposable, INotifyPropertyChanged

#Region " Declarations "
        Private _headerinfo As String
        Private _backgroundworker As BackgroundWorker

#End Region

#Region " Properties "
        Public Property HeaderInfo() As String
            Get
                Return _headerinfo

            End Get
            Set(ByVal value As String)
                If Not (value Is String.Empty) Or Not (IsNothing(value)) Then
                    _headerinfo = value
                End If

            End Set
        End Property

        Protected ReadOnly Property BackGroundWorker() As BackgroundWorker
            Get
                If _backgroundworker Is Nothing Then
                    _backgroundworker = New BackgroundWorker
                End If
                Return _backgroundworker
            End Get
        End Property

        Private _isdirty As Boolean = False
        Protected Property IsDirty As Boolean
            Get
                Return _isdirty
            End Get
            Set(ByVal value As Boolean)
                If Not Equals(value, _isdirty) Then
                    _isdirty = value
                    If _isdirty = True Then
                        DisableNavigation()
                    Else
                        EnableNavigation()
                    End If
                End If
            End Set
        End Property

        ''' <summary>
        ''' not a databinding property. No need for onpropertychanged notifications
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Protected Property IsLoading As Boolean = False

        Private _haschanges As Boolean
        Public Property HasChanges As Boolean
            Get
                Return _haschanges
            End Get
            Set(ByVal value As Boolean)
                If Not Equals(value, _haschanges) Then
                    _haschanges = value
                    If value = True Then
                        GetEvent(Of Events.DisableCloseButtonEvent).Publish(True)
                    End If
                    OnPropertyChanged("HasChanges")
                End If
            End Set
        End Property


#End Region

#Region " Dialogs "
        'This is not in Bases because it would cause circular references.

        ''' <summary>
        ''' Gets the IDialogService registered with the ServiceContainer.
        ''' use ShowMessage or ShowException in child code.
        ''' </summary>
        Private ReadOnly Property Dialog() As Dialog.IDialogService
            Get
                Return GetService(Of Dialog.IDialogService)()
            End Get
        End Property

        Protected Function ShowMessage(ByVal message As String, ByVal caption As String, ByVal button As Dialog.DialogButton, ByVal image As Dialog.DialogImage) As Ocean.OceanFramework.CommonDialog.CustomDialogResult
            GetEvent(Of Events.DialogShowingEvent).Publish(True)
            Dim rslt As CustomDialogResult = Dialog.ShowMessage(message, caption, button, image)
            GetEvent(Of Events.DialogShowingEvent).Publish(False)
            Return rslt
        End Function

        Protected Sub ShowException(ByVal message As String, Optional ByVal expandedMessage As String = Nothing, Optional ByVal image As Dialog.DialogImage = Core.Services.Dialog.DialogImage.Error)
            GetEvent(Of Events.DialogShowingEvent).Publish(True)
            Dialog.ShowException(message, expandedMessage, image)
            GetEvent(Of Events.DialogShowingEvent).Publish(False)

        End Sub
#End Region

#Region " Wait States "

        Private ReadOnly Property Wait As WavelengthIS.Core.Services.IWaitingService
            Get
                Return GetService(Of IWaitingService)()
            End Get
        End Property

        Protected Sub BeginWait()
            GetEvent(Of Events.DisplayWaitingControlEvent).Publish(True)
        End Sub

        Protected Sub EndWait()
            GetEvent(Of Events.DisplayWaitingControlEvent).Publish(False)
        End Sub
#End Region

#Region " Events "
        Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged


#End Region

#Region " Constructor "
        Public Sub New()
            _backgroundworker = New BackgroundWorker
            AddHandler _backgroundworker.DoWork, AddressOf BackGroundWorker_DoWork
            AddHandler _backgroundworker.RunWorkerCompleted, AddressOf BackGroundWorker_RunWorkerCompleted

        End Sub

#End Region

#Region " IDisposable Support "

        Private disposedValue As Boolean = False        ' To detect redundant calls

        ' IDisposable
        Protected Overridable Sub Dispose(ByVal disposing As Boolean)
            If Not Me.disposedValue Then
                If disposing Then
                    ' TODO: free other state (managed objects).
                End If

                ' TODO: free your own state (unmanaged objects).
                ' TODO: set large fields to null.
            End If
            Me.disposedValue = True
        End Sub
        ' This code added by Visual Basic to correctly implement the disposable pattern.
        Public Sub Dispose() Implements IDisposable.Dispose
            ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
#End Region

#Region " Debugging Helpers "
        <Conditional("DEBUG")> _
        Public Sub VerifyPropertyName(ByVal propertyName As String)

            'If you raise PropertyChanged and do not specify a property name,
            'all properties on the object are considered to be changed by the binding system.
            If String.IsNullOrEmpty(propertyName) Then
                Return
            End If

            ' Verify that the property name matches a real,  
            ' public, instance property on this object.
            'If TypeDescriptor.GetProperties(Me)(propertyName) Is Nothing Then
            '    Dim msg As String = "Invalid property name: " & propertyName
            '    Throw New Exception(msg)
            'End If
        End Sub

        Private _ThrowOnInvalidPropertyName As Boolean
        Protected Property ThrowOnInvalidPropertyName() As Boolean
            Get
                Return _ThrowOnInvalidPropertyName
            End Get
            Private Set(ByVal value As Boolean)
                _ThrowOnInvalidPropertyName = value
            End Set
        End Property




#End Region

#Region " INotifyProperty Changed Method "


        Protected Overridable Sub OnPropertyChanged(ByVal strPropertyName As String)
            Me.VerifyPropertyName(strPropertyName)

            If Me.PropertyChangedEvent IsNot Nothing Then
                RaiseEvent PropertyChanged(Me, New System.ComponentModel.PropertyChangedEventArgs(strPropertyName))
            End If


        End Sub

        Private Function QualifyString(ByVal str As String) As Boolean



            Return True

        End Function

        Protected Overridable Sub OnPropertyChanged(ByVal strPropertyName As String, ByVal IsPrimaryProperty As Boolean)
            Me.OnPropertyChanged(strPropertyName)

        End Sub

#End Region

#Region " Navigation Events "

        Protected Sub EnableNavigation()
            'Keep from firing multiple onPropertyChanged events
            If HasChanges = True Then
                HasChanges = False
            End If

            GetEvent(Of DisableNavigationEvent).Publish(False)

        End Sub

        Protected Sub DisableNavigation()
            'Keep from firing multiple onPropertyChanged events
            If HasChanges = False Then
                HasChanges = True
            End If

            GetEvent(Of DisableNavigationEvent).Publish(True)

        End Sub

#End Region
    End Class

End Namespace
1
  • This question is tagged with C#.
    – Mizipzor
    Jul 2, 2013 at 15:47