The following code is a refactoring of my previous MVVM approach (Fat Models, skinny ViewModels and dumb Views, the best MVVM approach?) in which I moved the logic and INotifyPropertyChanged implementation from the model back up into the ViewModel. This makes more sense, since as was pointed out, you often you have to use models that you either can't change or don't want to change and so your MVVM approach should be able to work with any model class as it happens to exist.
This example still allows you to view the live data from your model in design mode in Visual Studio and Expression Blend which I think is significant since you could have a mock data store that the designer connects to which has e.g. the smallest and largest strings that the UI can possibly encounter so that he can adjust the design based on those extremes.
Questions:
I'm a bit surprised that I even have to "put a timer" in my ViewModel since it seems like that is a function of INotifyPropertyChanged, it seems redundant, but it was the only way I could get the XAML UI to constantly (once per second) reflect the state of my model. So it would be interesting to hear anyone who may have taken this approach if you encountered any disadvantages down the road, e.g. with threading or performance.
The following code will work if you just copy the XAML and code behind into a new WPF project.
XAML:
<Window x:Class="TestMvvm73892.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestMvvm73892"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider
x:Key="DataSourceCustomer"
ObjectType="{x:Type local:CustomerViewModel}"
MethodName="GetCustomerViewModel"/>
</Window.Resources>
<DockPanel DataContext="{StaticResource DataSourceCustomer}">
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<TextBlock Text="{Binding Path=FirstName}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding Path=LastName}"/>
</StackPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<TextBlock Text="{Binding Path=TimeOfMostRecentActivity}"/>
</StackPanel>
</DockPanel>
</Window>
Code Behind:
using System;
using System.Windows;
using System.ComponentModel;
using System.Threading;
namespace TestMvvm73892
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
//view model
public class CustomerViewModel : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private DateTime _timeOfMostRecentActivity;
private Timer _timer;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
this.RaisePropertyChanged("FirstName");
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
this.RaisePropertyChanged("LastName");
}
}
public DateTime TimeOfMostRecentActivity
{
get
{
return _timeOfMostRecentActivity;
}
set
{
_timeOfMostRecentActivity = value;
this.RaisePropertyChanged("TimeOfMostRecentActivity");
}
}
public CustomerViewModel()
{
_timer = new Timer(CheckForChangesInModel, null, 0, 1000);
}
private void CheckForChangesInModel(object state)
{
Customer currentCustomer = CustomerViewModel.GetCurrentCustomer();
MapFieldsFromModeltoViewModel(currentCustomer, this);
}
public static CustomerViewModel GetCustomerViewModel()
{
CustomerViewModel customerViewModel = new CustomerViewModel();
Customer currentCustomer = CustomerViewModel.GetCurrentCustomer();
MapFieldsFromModeltoViewModel(currentCustomer, customerViewModel);
return customerViewModel;
}
public static void MapFieldsFromModeltoViewModel
(Customer model, CustomerViewModel viewModel)
{
viewModel.FirstName = model.FirstName;
viewModel.LastName = model.LastName;
viewModel.TimeOfMostRecentActivity = model.TimeOfMostRecentActivity;
}
public static Customer GetCurrentCustomer()
{
return Customer.GetCurrentCustomer();
}
//INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
//model
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime TimeOfMostRecentActivity { get; set; }
public static Customer GetCurrentCustomer()
{
return new Customer
{ FirstName = "Jim"
, LastName = "Smith"
, TimeOfMostRecentActivity = DateTime.Now
};
}
}
}
I like your sample above, I think it implements the spirit of MVVM. Just for clarification, though, the ViewModel code and the Model code should not be in the same source file as the actual Code Behind. In fact, I would argue that they should not be in the same project.
Here is MVVM as I understand it:
M - the Model is the data returned from the Business Layer (BL). This should be lightweight, containing read-only data. The Model classes are dumb and do not contain Update, Write, or Delete logic, and are generated by the BL as the result of requests, commands, actions, etc. The Model classes have no knowledge of the presentation needs of the consuming application, so they can be used by any manner of application. To really take advantage of this reusability, we want the Model classes to be independent of the UI project.
VM - the ViewModel contains the communications layer: it issues the requests to the BL and processes the results in a manner fit for presentation. Like the example above, it also receives the Model and reformats it for the particular presentation needs. Think of this as a "Binding Class". In the example above, the data is simply being moved from one object to the next, but the ViewModel would be responsible for such things as exposing a "FullName" type property or adding leading zeroes to a ZipCode. It is correct that the Binding Class is the one to implement INotifyPropertyChanged. And again, for reusability I would probably extract this layer into its own project as well. This would allow you to experiment with various UI options with no plumbing changes.
V - the View is bound to the Binding class object created in the VM. The View is super dumb: it knows nothing of the BL or the VM. Data can be bound in both directions, but the VM handles errors, validation, etc. Any data synchronization operations are handled by passing requests back the the BL, and again processing the results.
It would depend on the type of application, but it seems heavy handed to constantly check the Model to see if it has changed. Pretend you were connecting to a BL that built the Business Object(BO) from a DAL, which is connecting to a DB. In this scenario, you would be constantly recreating the BO, which I'm sure would be a performance killer. You could implement a checkout system on the BL that listened for notifications, or have a method for comparing last known time of change to actual, or you could cache the BO on the BL. Just some ideas.
Also, I said above that the Model should be Lightweight. There are heavyweight options, like CSLA, but I'm not sure how well they fit into the MVVM idea.
I don't mean to pass myself off as an expert, I have only been studying these ideas so far while designing our new software's architecture. I'd love to read some discussion about this topic.
My personal opinion is that while Model should be used to load and store data, ViewModel's responsibility is to know when this data is needed, thus using timer in a ViewModel makes sense. This way you can use your Model with different ViewModel (for which it may be sufficient to retrieve data only once, not every second).
Few things to consider:
Implement your model to support
Asynchronous data retrieval (very
important if you want to target Silverlight)
Be careful about updating collection from background thread (not a problem in your example, but if you ever need to use ObservableCollection than remember that it cannot be updated from non UI thread, read more here )
Related
I've created a Textbox with placeholder text and a clear button. I've implemented it using a view model for the data context, and using a style with target type TextBox. In xaml, using it is pretty simple.
<TextBox DataContext="{Binding NameBox}" Style="{StaticResource placeholder}"/>
The way I've implemented the view model, though, smells funny to me:
public class PlaceholderTextBoxViewModel : NotifiableViewModelBase {
private string text;
public string Text {
get => text;
set {
text = value;
OnTextChange(text);
}
}
public string PlaceholderText { get; set; }
public RelayCommand ClearCommand => new RelayCommand(() => Text = "");
private event Action<string> OnTextChange;
public PlaceholderTextBoxViewModel(ref string text, string placeholderText, Action<string> changeHandler = null) {
OnTextChange = changeHandler ?? (_ => { });
Text = text;
PlaceholderText = placeholderText;
}
}
In case it doesn't smell too bad to you yet, check out how it's used
private string _name;
public string Name {
get => _name;
set {
_name = value;
System.Console.WriteLine(_name); // needed to silence auto prop error
}
}
public PlaceholderTextBoxViewModel NameBox { get; }
// in the constructor...
NameBox = new PlaceholderTextBoxViewModel(ref _name, "Exam Name", t => Name = t);
It definitely doesn't seem right that I need to pass an explicit setter (the changeHandler) to the PlaceholderTextBoxViewModel. It seems, indeed, that the ref I'm passing is never really used (and is only necessary at all -- though not as a ref -- if there is to be pre-existing text in the box).
I've never used refs before and I must be doing something wrong. I have also tried pointing everything that uses the Name property (in the final code excerpt) to the _name field but that doesn't work, the field isn't properly updated, or at least isn't "communicating" its updates (in various uses, CanExecutes are not updated, SearchPredicates are not refreshed, etc). I'm using MVVMLight, and I imagine that changing a field's value doesn't trigger OnPropertyChanged -- if the field's value is even changing at all.
How do I get the ref to work correctly? Am I doing this completely wrong?
I understand that there are other ways to implement this TextBox with its clear command, even in pure MVVM (namely, if I put the ClearCommand in the consuming VM instead of the textbox's VM itself, then the textbox doesn't need to have a VM at all). But I'd really like to know how to make sense of my attempted solution, if only for a better understanding of C# and of refs.
Problem here seems to be an architectural one. MVVM is a tiered architecture that looks like this:
Model -> View Model -> View
Model is the lowest tier, view is the highest. More importantly, each tier does not have any direct visibility into any of the tiers above it.
The problem in your example is that you've broken separation of concerns. You have a parent class creating the PlaceholderTextBoxViewModel, which implies it's in the view model. However, that same class contains a "Name" property, which is actually data that should be in your model layer. Your existing architecture is such that your view model cannot see the data layer, so you've effectively had to set up your own property change notification mechanism, using the ref and delegate, to keep your model and view model synchronized.
Throw it all out, and start again. Your model should contain POCOs, so start with something like this:
public class MyModel
{
public string Name {get; set;}
}
Then, when you create your view model, pass an instance of this class into its constructor so that it has visibility:
public class MyViewModel : NotifiableViewModelBase
{
private MyModel Model;
public MyViewModel(MyModel model) => this.Model = model;
public string Text
{
get => this.Model.Name;
set
{
this.Model.Name = value;
RaisePropertyChanged(() => this.Text);
}
}
// ... etc ....
}
I've stuck to your nomenclature of using "Name" in the model and "Text" in the view model, in practice they're usually the same, but that's up to you. Either way, you still have property change notification in your view model, and it's the view model layer updating the model layer.
Obviously there are lots of variations on this. If you don't want changes to propagate through to your model layer immediately (and there are plenty of cases where you may not want that) then give Text a backing field (_Text) and only do the synchronization at the points your want it to occur. And of course, if you want to go one step further then your model classes could instead implement interfaces, and you can use dependency injection to inject those interfaces into the view model classes instead of giving them access to the actual implementations themselves.
Above all else, keep in mind that the sole purpose of the view model is to prepare the model layer data for consumption by the view. Anything else...data, domain, business logic etc...all of that belongs in your model layer, which shouldn't have any visibility into the view model layer at all.
The ref would only make sense, if you are going to change the value.
In this case you can use the OnTextChange event.
public PlaceholderTextBoxViewModel(ref string text, string placeholderText, Action<string> changeHandler = null)
{
OnTextChange = newValue =>
{
text = newValue; // <- value back to the ref
changeHandler?.Invoke(newValue);
}
Text = text;
PlaceholderText = placeholderText;
}
BTW your solution is somehow much too complicated. Keep the ViewModel as simple and abstract as possible. In this case a simple Name property is enough.
Leave it up the the UI developers which control they use and how they will implement a clear the control logic.
Here an example
ViewModel
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
namespace WpfApp1
{
public class MainViewModel : ReactiveObject
{
[Reactive] public string Name { get; set; }
}
}
View
<Window
x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<local:MainViewModel />
</Window.DataContext>
<Grid>
<StackPanel
Width="200"
VerticalAlignment="Center">
<Label Content="{Binding Name}" />
<DockPanel>
<Button
DockPanel.Dock="Right"
Content="x"
Width="20"
Click="NameTextBoxClearButton_Click"/>
<TextBox x:Name="NameTextBox"
Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
TextWrapping="Wrap" />
</DockPanel>
</StackPanel>
</Grid>
</Window>
View CodeBehind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void NameTextBoxClearButton_Click( object sender, RoutedEventArgs e )
{
NameTextBox.Text = string.Empty;
}
}
The simplest solution would be to correct your binding. You don't have to manually forward the data by trying to implement your own change notification system.
Just make sure that your data source always implements INotifyPropertyChanged and properly raises the INotifyPropertyChanged.PropertyChanged event from each property set method. Then bind directly to this properties:
class PlaceholderTextBoxViewModel : INotifyPropertyChanged
{
private string text;
public string Text
{
get => this.text;
set
{
this.text = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
The binding syntax allows to reference nested properties.
In your special case, the {Binding} expression must be:
<TextBox DataContext="{Binding NameBox.Text}" />
Now the TextBox.Text value is automatically propagated to the PlaceholderTextBoxViewModel.Text property and the constructor becomes parameterless.
This question already has answers here:
MVVM in WPF - How to alert ViewModel of changes in Model... or should I?
(11 answers)
Closed 5 years ago.
Based on the picture from MSDN
It seems like all the data and business logic should be inside Model where View Model should have a duplicated set of properties of the Model for display purposes. And View should bind to the duplicated property inside the ViewModel instead of binding to the properties inside Models directly.
ViewModel should implements INotifyPropertyChanged interface to let View know if certain property is changed.
But how should Model notify ViewModel about changes? Should it implement INotifyPropertyChanged as well? If so then we could just have the View bind to the Model's property directly. Whats the real benefit of having an extra layer in between and we have to manually handle all the data changed notifications?
example based on my understanding:
View:
<Grid>
<TextBlock Text="{Binding foo}"/>
<Label Content="{Binding bar}"/>
</Grid>
View Model:
class ViewModel : INotifyPropertyChanged
{
Model _m;
public ViewModel(Model m)
{
_m = m;
}
public string foo
{
get
{
return _m.foo;
}
set
{
_m.UpdateFoo(value);
//This one works fine. xaml will call getter to get the dead beef version
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("foo"));
}
}
public string bar
{
get
{
return _m.bar;
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Model:
class Model
{
public string foo { get; private set; }
public string bar { get; private set; }
public void UpdateFoo(string newVal)
{
foo = newVal + "dead beef";
bar = newVal; //how do i tell ViewModel that i have changed?
}
}
Notifications can come from the model via INotifyPropertyChanged; but realistically that interface is horrible to consume manually. Having to base your logic based off the name of the changed property is not fun.
A model layer with notifications could be something like a message bus client, as messages come in it parses it and sends relevant (and strongly typed) events to the view model. The view model then updates properties on its data objects that raise PropertyChanged.
To your bigger question: Do you have to have separate ViewModel and Model data objects?
NO
If you want to be a purist, sure; duplicate your objects. If you want a rational approach, only have special view model objects if you need to add properties that wouldn't be appropriate (or just cant exist on) a model object.
The model is much more about separation of concerns than a useless set of duplicate objects. In the previous example, the ViewModel should not care that the objects or events came from a message bus, it just knows how to set up the objects for the view. The Model handles the implementation detail of being a message bus client.
Okay. So what I need to do is to initialize a ViewModel using a constructor. The problem is I can't create the constructor due lack of knowledge. I'm new to MVVM (or c# in general for that matter) and had to get some help to implement this code:
public class ViewModel
{
private static ViewModel instance = new ViewModel();
public static ViewModel Instance
{
get
{
return instance;
}
}
}
However, I fail to create a constructor to place this code.
DataContext = ViewModel.Instance
It is meant to go into two different pages to pass a value between TextBoxes.
I'm also confused as to whether I should put the ViewModel in both the main window and the page or in just one of the two.
So, anyone can help?
Follow this pattern:
This part is how your model classes should look like,
Even if you use entity framework to create your model they inherit INPC.. so all good.
public class Model_A : INotifyPropertyChanged
{
// list of properties...
public string FirstName {get; set;}
public string LastName {get; set;}
// etc...
}
each view model is a subset of information to be viewed, so you can have many view models for the same model class, notice that in case your make the call to the parameter-less c-tor you get auto instance of a mock model to be used in the view model.
public class ViewModel_A1 : INotifyPropertyChanged
{
public Model_A instance;
public ViewModel()
{
instance = new instance
{ //your mock value for the properties..
FirstName = "Offer",
LastName = "Somthing"
};
}
public ViewModel(Model_A instance)
{
this.instance = instance;
}
}
And this is for your view, if you view in the ide designer you will have a mock view model to show.
public class View_For_ViewModelA1
{
public View_For_ViewModel_A1()
{
//this is the generated constructor already implemented by the ide, just add to it:
DataContext = new ViewModel_A1();
}
public View_For_ViewModel_A1(ViewModel_A1 vm)
{
DataContext = vm;
}
}
XAML Side:
<Window x:Class="WpfApplication1.View_For_ViewModel_A1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ViewModel="clr-namespace:WpfApplication1"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"
d:DataContext="{d:DesignInstance ViewModel:ViewModel_A1, IsDesignTimeCreatable=True}"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBox Text="{Binding FirstName}" />
<TextBox Text="{Binding LastName}" />
</Grid>
</Window>
In a more advanced scenario you would want to have a single view model class to relate to several model classes.. but you always should set a view to bind to a single view model.
if you need to kung-fu with your code - make sure you do that in your view model layer.
(i.e. creating a view-model that have several instances of different model types)
Note: This is not the complete pattern of mvvm.. in the complete pattern you can expose command which relate to methods in your model via your view-model and bind-able to your view as well.
Good luck :)
I basically follow this pattern:
public class ViewModelWrappers
{
static MemberViewModel _memberViewModel;
public static MemberViewModel MemberViewModel
{
get
{
if (_memberViewModel == null)
_memberViewModel = new MemberViewModel(Application.Current.Resources["UserName"].ToString());
return _memberViewModel;
}
}
...
}
To bind this to a page is:
DataContext = ViewModelWrappers.MemberViewModel;
And if I'm using more than 1 ViewModel on the page I just bind to the wrapper.
DataContext = ViewModelWrappers;
If you or anybody else, who's new to the MVVM, gets stuck here, for example at the "INotifyPropertyChanged could not be found". I recommend trying some example-MVVM's or tutorials.
Some I found useful:
http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial
https://www.youtube.com/watch?v=EpGvqVtSYjs&index=1&list=PL356CA0B2C8E7548D
I am trying to implement MVVM for one of my Windows Phone app that i am developing and its growing to be big.
I have tried below code in Model class.I want to know how can i handle the scenario where user clicks on a button "Latest Entry" and it will connect to a service and executes a method asynchronously.Once the data is returned i have to display the latest record in UI which has 3 text fields EmpName,EmpID,Address.
Code in Model Class:
public class EmpDetailsModel:INotifyPropertyChanged
{
private string _EmpName;
public string EmpName
{
get { return _EmpName; }
set {
if (value != _EmpName)
{
_EmpName = value;
RaisePropertyChanged("EmpName");
}
}
}
private string _EmpId;
public string EmpId
{
get { return _EmpId; }
set {
if (value != _EmpId)
{
_EmpId = value;
RaisePropertyChanged("EmpId");
}
}
}
private string _Address;
public string Address
{
get { return _Address; }
set {
if (value != _EmpId)
{
_EmpId = value;
RaisePropertyChanged("Address");
}
}
}
#region myfirstmodel inotify members
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
The code to connect to service is below:
EmpAzureSer empAzureSer = new EmpAzureSer();
empAzueSer.GetLatestEntry += new GetLatestEntryCompletedEventHandler(LatestEntryCompleted);
private void LatestEntryCompleted(object sender, GetLatestEntryCompletedEventArgs e
{
//get the data from e as e.Name,e.Id and e.Address and bind them to UI.
}
view xaml code:
<Button Name="FetachLAtest" Click="FetachLatest_Click"></Button>
<TextBlock Name="EmployeeName"></TextBlock>
<TextBlock Name="EmployeeID"></TextBlock>
<TextBlock Name="EmployeeAddress"></TextBlock>
I was following the link http://msdn.microsoft.com/en-us/library/windowsphone/develop/gg521153(v=vs.105).aspx.
It was very helpful but I want to know where do i put the code to connect to service (model ? or Viewmodel ? How does the viewmodel should look like ?
There are various ways to implement MVVM into an application, it varies depending on developpers and application requirements.
But for started, let's try to keep things simple and to focus on ViewModels (because this seems to be where is your interest).
MVVM means Model View ViewModel, Model is your business/domain code, View is basically your XAML and its associated code behind, and ViewModel is the link/glue between Views and Models.
An important thing to note is that ViewModels mustn't know Views (meaning don't reference them). This ensures a better separation of concerns, and thus try to build an application easier to test and to maintain.
So to make a long story short, ViewModels don't know Views but they have to communicate with them... And this magic is made possible thanks to Bindings!
XAML/UI components display data, these data comes from the ViewModel which is bound to the View through Bindings mechanisms (provided on WP by the Silverlight framework).
This means the ViewModel contains all the data required by the View, actually a ViewModel represents all the data or behaviors of a View.
Being not the best person to describe the whole MVVM pattern and all its subtilities, i'll leave this sensitive task to most knowledgeable people in the field ;). Here are some really great links that should help you :
From Josh Smith
Wikipedia with code samples for ViewModel
If you already know MVC or MVP patterns, this one will help you to spot differences
All this being told, you must be a little bored with theory, so let's try to write some code. The problem is that there are many ways to organize your code, so all that follow is just a kind of pseudo code, it cannot be used directly into your application!
In your case, you could create just a ViewModel like this one
public class WhateverYouWantViewModel : INotifyPropertyChanged
{
private EmpDetailsModel _model;
public EmpDetailsModel Model
{
get { return _model; }
set
{
if (value != _model)
{
_model = value;
RaisePropertyChanged("Model");
}
}
}
public void GetLastestEntries()
{
// put in here the code calling your service
}
}
About assignements from data service to your this.Model, we are dealing with an asynchronous callback, so maybe it would be wiser to use the Dispatcher in case the callback is not called from the UI Thread :
EmpAzureSer empAzureSer = new EmpAzureSer();
empAzueSer.GetLatestEntry += new GetLatestEntryCompletedEventHandler(LatestEntryCompleted);
private void LatestEntryCompleted(object sender, GetLatestEntryCompletedEventArgs e
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.Model = new EmpDetailsModel()
{
//get the data from e as e.Name,e.Id and e.Address and bind them to UI.
};
});
}
Creating a new EmpDetailsModels before assigning it to this.Model will trigger RaisePropertyChanged and notify the View this property has changed. More specifically, the UI component bound to this property will be notified for being updated.
To bind your UI components to the ViewModel, you can do something like that :
<Button Name="FetachLAtest" Click="FetachLatest_Click"></Button>
<TextBlock Name="EmployeeName" Text="{Binding Model.EmpName}"></TextBlock>
<TextBlock Name="EmployeeID" Text="{Binding Model.EmpId}"></TextBlock>
<TextBlock Name="EmployeeAddress" Text="{Binding Model.Address}"></TextBlock>
Do not forget to set the DataContext of your View with your ViewModel instance.
Last but not least, you have to bind your "Latest Entry" Button to the ViewModel.GetLastestEntries method by calling it from your *View.FetachLatest_Click* event handler. All this can be achieved this way :
public partial class YourView : BasePage
{
private WhateverYouWantViewModel _viewModel;
public YourView()
{
InitializeComponent();
_viewModel = new WhateverYouWantViewModel();
this.DataContext = _viewModel;
}
private void FetachLatest_Click(object sender, RoutedEventArgs e)
{
_viewModel.GetLastestEntries();
}
}
And that's (almost) it! Why almost? Because the link between the View and the ViewModel is quite strong and defined into the code behind (which is something we are usually trying to avoid in MVVM).
Fortunately, there are some solutions to solve this issue :
What we call a ViewModelLocator could be used to store and to locate
ViewModels
A Command could be created in WhateverYouWantViewModel and bound to the "Lastest
Entry" Button, instead of calling directly the GetLastestEntries method in code behind
The downside of all this is that you would have to write more code and that's where MVVM framweworks come up! These frameworks will help you to write clean MVVM applications with minimum effort.
As a beginner, i would warmely advice you to visit MVVM Light Toolkit website. It contains lots of useful articles about the MVVM pattern, to learn how to design an MVVM application and to handle common scenarii using this framework. MVVM Light is not the only MVVM framework running on Windows Phone but i'm quoting it because it is widely used, it has a big community and it strives to keep things as simple as possible.
I'm aware this answer is only a starting point to achieve what you want. I only give you some ideas that need further study, but i hope it will help you move in the right direction.
I am trying to come up with a good way of implementing the MVVM pattern using Entity-Framework where my entities are my models. My DataContext is my viewmodel. This is a small reproduction of the problem.
View
<TextBox Text="{Binding MyText}" />
ViewModel:
I have the requirement of needing to navigate record by record from my DB. When a button is clicked in the View a command is sent to the Viewmodel that executes nextRecord(). EF does its magic and _myObject is the next row/record from the database
public class myViewModel: INotifyPropertyChanged
{
private MyEntityObject _myObject;
public string MyText
{
get { return _myObject.MyText; }
set
{
if (_myObject.MyText != value)
{
_myObject.MyText = value;
OnPropertyChanged("MyText");
}
}
}
private void _nextRecord()
{
_myObject = myEntitiesContext.NextRecord() //pseudocode
}
}
Autogenerated Entity Model
public partial class MyEntityObject
{
public string MyText { get; set; }
}
Since the View has no knowledge of _myObject changing, it doesn't update when _myObject changes. A few approaches I have thought of.
I haven't tested wrapping my entities in a INotifyPropertyChanged wrapper class but am wary to do this as I have a lot of entity objects.
I could call OnPropertyChanged("...") for all properties, but some of my entities have a lot of properties to them, which would be ugly. Possible to use reflection to make it cleaner, but I may have properties that aren't databound.
I might be able to defer this to the UI, somehow refreshing the bindings when I click "Next Record", but this breaks MVVM and looks dirty
How can I get the UI to recognize changes from _myObject?
As I've mentioned in the comments, calling OnPropertyChanged("") or OnPropertyChanged(null) invalidates all properties and is equivalent to calling OnPropertyChanged for each and every property. This behavior is also documented here:
The PropertyChanged event can indicate all properties on the object
have changed by using either null or String.Empty as the property name
in the PropertyChangedEventArgs.
This means that you can simply add a call to OnPropertyChanged("") when you update your object to force WPF to reevaluate all bindings to your view model:
private void _nextRecord()
{
_myObject = myEntitiesContext.NextRecord();
OnPropertyChanged("");
}
That being said, I'd still go with #Anand's solution (+1). There's an ongoing debate on whether it's OK or not for the viewmodel to expose the model as a property, and I tend to go with exposing it until you need to introduce some view model specific logic. Most of the time you won't have to and it's not worth the trouble of wrapping model properties.
The problem with your code is that when _myObject changes the MyText property changed event is not fired. A work around would be to create a new property to hold you entity
and make this property as your Grids DataContext in your view as shown below. Now when this line is executed MyObject = myEntitiesObject.NextRecord() your view will be notified about the change.
public class myViewModel : INotifyPropertyChanged
{
private MyEntityObject _myObject;
public MyEntityObject MyObject
{
get { return _myObject; }
set {
if (_myObject != value)
{
_myObject = value;
OnPropertyChanged("MyObject");
}
}
}
private void _nextRecord()
{
MyObject = myEntitiesObject.NextRecord() //pseudocode
}
}
View:
<Grid DataContext="{Binding MyObject}">
<TextBlock Text="{Binding MyText}"/>
</Grid>
An extremely simple but not very elegant solution that I believe would meet needs: upon switching records, set the DataContext to null, then back to the ViewModel.
However, there are arguably more elegant alternatives that require more work to meet all requirements. See Anand's answer for an improvement upon this.
The tag in View should have the mode and UpdateSourceTrigger attribute set with values.