Presentation is loading. Please wait.

Presentation is loading. Please wait.

MVVM Overview Frank Shoemaker MindCrafted Systems

Similar presentations


Presentation on theme: "MVVM Overview Frank Shoemaker MindCrafted Systems"— Presentation transcript:

1 MVVM Overview Frank Shoemaker MindCrafted Systems frank@mindcrafted.com

2 Some background Some examples Overview of MVVM

3 MVVM stands for M odel V iew V iew- M odel MVVM

4 Simple Case

5 Typical class that covers a database Could be a WCF Service and its client reference Model

6 Provides data to and from the View Responds to both the View and the Model Informs the View of changes in the data Reusable (at least much more than code behind a form) ViewModel

7 Knows nothing about the View Does not push data into the view TextBox1.Text = object.Name() ViewModel

8 Uses Binding to subscribe to the ViewModel Interprets business data and state of ViewModel to the human Nothing but Presentation - XAML No or minimal code-behind View

9 WPF/Silverlight data binding is what makes things work ViewModel presents a published interface to the View Binding in the XAML instead of code More use of Declarative Programming More on the ViewModel in MVVM

10 Architecture

11 Existing Stuff Database Tables

12 Existing Stuff Library Class

13 WPF

14 Business data Properties Properties to return Select lists (AllSelect and StatusSelect) The usual CRUD routines Model Class

15 Encapsulates how it communications with the back-end Uses Events to signal I/O successfully completed or an error occurred In WPF its synchronous, but can be used as if its a asynchronous. In Silverlight its async. Model Class

16 Public Sub Read(ByVal id As Integer) Try myLibraryObj.MCFetch(id) RaiseEvent IOSuccessful("Read", New EventArgs()) Catch ex As Exception RaiseEvent IOErrorOccurred("Read", ex) End Try End Sub Model Class – I/O WPF - Synchronous

17 Public Sub Read(ByVal id As Integer) Try myService.FetchAsync(id, ServiceReference1.myContextPayloadType.Heavy) Catch ex As Exception RaiseEvent IOErrorOccurred("Read", ex) End Try End Sub Model Class – I/O Silverlight - Asynch

18 Private Sub Read_Completed(ByVal sender As System.Object, ByVal e As ServiceReference1.FetchCompletedEventArgs) Handles myService.FetchCompleted If IsNothing(e.Error) Then myData = e.Result RaiseEvent IOSuccessful("Read", New EventArgs()) Else RaiseEvent IOErrorOccurred("Read", e.Error) End If End Sub Model Class – I/O Silverlight - Asynch

19 Properties come in two flavors Data Properties Name, StatusID, CreateDate, AllSelect Form State properties IsEditing, IsNotEditing, IsOKToBeginEdit ViewModel Properties

20 Methods come in two flavors CRUD Methods Create, Read, Update, Delete Implements the IEditableObject interface BeginEdit, CancelEdit, EndEdit ViewModel Methods

21 Implements INotifyPropertyChanged interface Notify the View that a property has changed its value Allows the View to respond to reflect the change, if it wants to ViewModel Class Events

22 Present some properties in more than one way for the convenience of the View IsEditing True if the user is currently editing the business object IsNotEditing True if the user is NOT currently editing the business object. ViewModel Class Properties

23 DataContext Binding Gluing the Pieces Together

24 This example sets up the DataContext in code Create a new instance of the ViewModel Bind the View to the ViewModel Instance All Controls on the View then inherit the DataContext from the page. Setup the DataContext

25 Private Sub Page_Loaded (ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) myVM = New ViewModel.DepartmentVM() ' Set the DataContext for the ' entire page to the ViewModel Me.DataContext = myVM End Sub Set up the DataContext

26 Public Event PropertyChanged(ByVal sender As Object, ByVal e As PropertyChangedEventArgs) _ Implements INotifyPropertyChanged.PropertyChanged Data Binding - ViewModel INotifyPropertyChanged

27 Public Property CreatedBy() As String Get Return myModel.CreatedBy End Get Set(ByVal value As String) myModel.CreatedBy = value RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("CreatedBy")) End Set End Property Data Binding - ViewModel Deparment.CreatedBy

28 < TextBox Text="{Binding Path=CreateDate, Mode=OneWay }"... Path is within the DataContext Mode=OneWay means the control wont update the ViewModel Since its bound to CreateDate, when the PropertyChanged event is raised the control reloads from the CreateDate property in the ViewModel Controls dont need to be named Data Binding - View Deparment.CreatedBy

29 <TextBox Text="{Binding Path=Name, Mode=TwoWay, IsEnabled="{Binding Path=IsEditing}"... Binding to interpret the ViewModels state to the user. Binding For State

30 <Button Name="Edit" Content="Edit" IsEnabled="{Binding Path=IsOKToBeginEdit}" Click="Edit_Begin"... <Button Name="Save" Content="Save" IsEnabled="{Binding Path=IsEditing}" Click="Edit_Save"... <Button Name="Cancel" Content="Cancel" IsEnabled="{Binding Path=IsEditing}" Click="Edit_Cancel"... Binding for State

31 <TextBox Text="{Binding Path=Name, Mode=TwoWay,... Bi-directional binding. TwoWay Data Bindning

32 <TextBox Text="{Binding Path=Name, Mode=TwoWay, ValidatesOnExceptions=True}"... When the ViewModel throws the exception, the View changes Validating in the ViewModel

33 ... <Setter Property="Validation.ErrorTemplate" Value="{StaticResource errorEyeCatcher}"/> <Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}"/> Setting up Styles for Validation Binding

34 Setting up Styles for Validation Binding

35 <TextBox Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus, ValidatesOnExceptions=True}" IsEnabled="{Binding Path=IsEditing}"... When to Validate?

36 <ComboBox ItemsSource="{Binding Path=StatusSelect}" DisplayMemberPath="Value" SelectedValuePath="Key" SelectedValue="{Binding Path=StatusID, Mode=TwoWay}"... ComboBox Binding

37 The state of Editing is maintained by the ViewModel ViewModel exposes properties to indicate state View interprets the ViewModels state to the user Data Binding ViewModel.FormStateMessage

38 <TextBlock Text="{Binding Path=FormStateMessage}"... Displaying the Status Message

39 <TextBlock Text="{Binding Path=FormStateMessage}" Foreground="{Binding Path=FormStateMessageType, Converter={StaticResource MessageForegroundColor}, ConverterParameter=FormStateMessageType}"... Use a converter routine to transform integer from the ViewModel into a color on theTextBox Binding to Change Color of the Message if its an Error

40 Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _ As Object Implements System.Windows.Data.IValueConverter.Convert If CInt(value) = 1 Then ' Informational message Return "Black" Else ' Error message Return "Red" End If End Function Converter Routine

41 Setup the Converter Routine as a Resource in the XAML

42 Since ViewModels know nothing about the UI, they can be driven with a programmatic test case. Testing

43 Loose coupling between the Model, ViewModel, and View Bright lines between areas of concerns At least some chance of reusability of the ViewModel ViewModel is independently testable MVVM Wrap up

44 View can be worked on by designers without messing up the ViewModel Would benefit from a root ViewModel class for the state management. MVVM Wrap up


Download ppt "MVVM Overview Frank Shoemaker MindCrafted Systems"

Similar presentations


Ads by Google