Showing posts with label MVVM. Show all posts
Showing posts with label MVVM. Show all posts

Thursday, July 31, 2014

MVVm views without C# code behind file

The MVVm is a great technique for separating the concerns. If we take ASP.Net MVC we can see it is built for using model view controller model. So by default wont allow us to write code behind for the views (We can write inside the cshtml though). But WPF as the technology was not built to use WPF to there is no in-built way to avoid the code behind of views. 

If the development team is so technology focused, it doesn't matter as they won't break the rules of MVVm even if there is code behind file. But since companies are offshoring to get cheap labor, enforcing quality is little tricky. As always cheap things comes with less quality. Most of the time people's priority is to get things done in quick way ie by writing everything in code behind instead of going through viewmodel. 

The challenge here is how to bring quality with these less skilled labor? One of the way to enforce viewmodel  usage is to delete the code behind of views which is nothing but the user controls.

If we just remove the usercontrol.xaml.cs, it will fail as the Initialize method is missing. So how to overcome is?

Add the Initialize method in the view itself. Yes we can write C# code in XAML. So the view user control will look as follows.

<UserControl x:Class="Joymons.MVVmDemo.Views.MainView"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <x:Code>
        <![CDATA[ public MainView() { InitializeComponent(); }]]>
    </x:Code>
            <TabControl ItemsSource="{Binding ChildVMs}" SelectedIndex="0">
                <TabControl.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Header}" />
                    </DataTemplate>
                </TabControl.ItemTemplate>
            </TabControl>
</UserControl>

I too started using VS 2013. That is why a black background in the code :)

Thursday, July 3, 2014

Binding Viewmodel property to tabitem header in MVVm pattern

Its been a while since I started a WPF project from scratch. I was mainly into the architectural side of application rather than UI side. Today I got an opportunity to start one app. It is supposed to be simple WPF application where the screens are arranged in hierarchical tabs.

The application is supposed to be a temporary application which will be used to test an algorithm developed by the business before its getting integrated into the actual application. So thought of not following the MVVm pattern as its supposed to be developed from our offshore in less amount of time. But one discussion with my lead architect changed my decision. If we are doing something we should do it right. We don't know whether the client will get rid of the application if it feels too good for them. Finally decided to go with MVVm.

The initial decision I had to take about the MVVm infrastructure. Earlier when I used to start the project I take my own RelayCommand,ViewmodelBase classes. That was the beginning time of WPF. But this time I decided to use a good library on the assumption that the MVVm framework must be matured by now. It ends up in using MVVM Light. Its a nice library which we can get from nuget.

Then started thinking about the UI structure where the tabs needs to be shown in hierarchical way. Its nothing but there will be one parent level tab control and in every tab page there will be one more tab control. I created the view models and bound to the view. Each high level view model have ChildVMs collection. In the MainPage.xaml UI I was able to bound to the ChildVMs property and they showed up as each and every viewmodel was associated with data template.

    <Application.Resources>
        <DataTemplate DataType="{x:Type vms:ChildViewmodel_1}">
            <vws:ChildViewUserControl_1/>
        </DataTemplate>
    </Application.Resources>

But I faced one problem. I could see that the tab headers are also showing the same control which is inside the tab page. Ideally I need to edit the tab header template and bind to the header property in the viewmodel. But I could see one more way which is just a data template for the tab item.

        <TabControl ItemsSource="{Binding ChildVMs}">
            <TabControl.ItemTemplate>
               
                <DataTemplate>
                    
                    <TextBlock Text="{Binding Header}" />
                </DataTemplate>
            </TabControl.ItemTemplate>
        </TabControl>

Happy coding

Friday, February 24, 2012

MVVm - Embed C# code in XAML like ASP.Net MVC

It is long time since I posted something in this blog. I know this is my most famous blog with average 200hits/day but I was mainly concentrating into the other aspects of .Net such as CLR, WCF, ASP.Net, Windows Phone 7 etc than this XAML based display technology. There are 2 main inspirations for this post.

First one is a comment which I got on my post related to opacitymask and its usage in WPF. The specialty of that is, it came from a MSFT guy. I don't know how others are thinking, but for me its little important. Even I am not sure whether that MSFT is just something else or that person just added MSFT :-)

The second reason is "This is my 100th post on WPF technology and I want that to be something special and useful". I was in search for such a topic and just found today, while I was working with ASP.Net MVC 3 application.

The problem
Anyway I am not wasting time on introduction.Lets come to the topic. As everybody knows MVVm is the widely accepted pattern for the XAML based technologies such as WPF and Silverlight. The main reason I could see is the data binding support. By design the pattern is not expecting anything in the code behind and everything related to business should reside in the viewmodel. Its all fine.We can have data binding and commands to separate the view from vm. But what can I do with the dialogs? Since they are UI is that desirable to call showdialog from viewmodel or should I write code behind for views and pass the dialog result to vm through event aggregator or any other messaging mechanism? Mainly this comes into picture when we need to browse for a file or show a messagebox in MVVm based application.

There are something called behaviors and triggers in an expression blend dll named System.windows.interactivity which we can leverage to accomplish the same. But are there any better way? Yes another way is to call the ShowDialog from the vm itself and process it. This is what I was following till I came to play more with ASP.Net MVC pattern.

What is special with ASP.Net MVC
MVC is another UI pattern to separate the UI from its business. When Microsoft implemented a framework to write asp.net applications using the same, people started calling it as ASP.Net MVC. Actually there is no relation between ASP.Net and MVC .Anybody can implement MVC in their application without MSFT framework.

The specialty I noticed in MVC framework is, there is no option to write code behind. In the RAZOR view we cannot even find a code behind file. I wondered how people are accomplishing their tasks without writing the code behind for views. Theoretically we can say "don't write code behind" .But I have never seen a big enterprise application in MVVm without code behind for at least one view.Coming back to ASP.Net MVC, the RAZOR don't give us option to write code behind but provides support to embed code inside the view itself.
Yes the idea flashed in my head and I could recollect one of my old post which explains embedding code    inside the xaml file .That is the way to handle the dialog boxes better.

Solution : Embed C# or VB.Net code in xaml view
This doesn't mean we should move the code behind file into the view. This helps to write the dialog handling code in the view itself. Below is one example of such an implementation.


    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <TextBox x:Name="txtFileName"
                 Text="{Binding FilePath,UpdateSourceTrigger=PropertyChanged}" />
        <Button Grid.Column="1" Content="Browse" Click="Clicked" />
        <x:Code>
            <![CDATA[
void Clicked(object sender, RoutedEventArgs e)
{
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.DefaultExt = ".exe";
            ofd.Filter = "Executables (.exe)|*.exe"; // Filter files by extension

            // Show open file dialog box
            Nullable<bool> result = ofd.ShowDialog();
            // Process open file dialog box results
            if (result.HasValue && result.Value)
            {
                // Set value to textbox which will update the property of VM
                txtFileName.Text= ofd.FileName;
            }
}
]]>
        </x:Code>
        <Button Content="Start"
                Grid.Column="2"
                Command="{Binding StartCommand}" />
    </Grid>

Pros and Cons
One thing to notice is that we need to give name to the controls which other developers may use to write code behind.Next thing how to show a message dialog box in this way .For that we need to keep a property in the vm and bind to a hidden textbox . Wire the TextChanged event of textbox to an event handler in the view as how the above C# code is written .
Main development challenge will be how to write code without intellisense .Yes you don't get intellisense when writing code inside xaml file.One way to overcome is to write the code in normal file and copy paste.

Monday, February 1, 2010

Type safe INotifyPropertyChanged

Usually we pass the property name as string from the setter of properties and raise the INotifyPropertyChanged.PropertyChanged event.This is not type safe as you.There are chances that the end developers may misspell the property name.The below link gives a great idea to make your OnPropertyChanged calls type safe.

http://mfelicio.wordpress.com/2010/01/10/safe-usage-of-inotifypropertychanged-in-mvvm-scenarios/

Saturday, May 16, 2009

MVVM CommandReference and KeyBinding

Recently when I was digging into MVVM sample in codeplex I came to notice one class named CommandReference.That class just contains a dependency property which is of ICommand.At first, I didn’t get why they created that class.But after seeing it’s application in the sample,I decided to add that in my MVVM.Core project because that was important when we come to a situation where  we need to bind a command to non dependency properties.Eg :InputBinding.Command
If you still didn’t get the importance of CommandReference just try to Bind a command to a KeyBinding as follows.

<Window.InputBindings>
<KeyBinding Modifiers="Control"
Key="N"
Command="{Binding CreateCustomerCommand}" />
</Window.InputBindings>


The result will be an Exception



A 'Binding' cannot be set on the 'Command' property of type 'KeyBinding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject



Reason is simple the Command property is not DependencyProperty.To get rid of this we have to use the CommandReference.The usage is as follows.



<Window.Resources>
<coreView:CommandReference x:Key="newCust"
Command="{Binding NewCustomerCommand}" />
</Window.Resources>
<Window.InputBindings>
<KeyBinding Modifiers="Control"
Key="N"
Command="{StaticResource newCust}" />
</Window.InputBindings>

See the sample for more details.This is again a modified version of Josh Smith's MVVM sample.

Tuesday, May 12, 2009

MVVM Communication among ViewModels

When a new person enters into the MVVM world ,the first doubt in his mind would be ‘How can I achieve messaging among View-Models ? ’or ‘How to notify other ViewModels about a change or operation in one ViewModel ?’ For example if we take a scenario of CRUD database operations there should be notifications passing through on each operation like creation,deletion etc...Otherwise the listing ViewModel will not be up to date.

When the same view-model communication came in to my mind, the possible solutions I got are

  1. Events : Raising events on operations so that subscribed view models will get notification.
    1. Data access layer / Data repository / Data provider  owns events
    2. View models own events.
  2. Mediator pattern : A centralized place where the subscriptions or handlers are stored against messages.

1.Events

This is the common solution found in most of the MVVM implementations.This is very easy to implement too.After each operation an event will get fired and the subscribed viewmodels will update themselves according to that.When we came to implement this method ,the common question would be where we should write these events.There are 2 places where we can write these events.

Events at data layer

The sample contained in the Josh Smith’s article uses this method.Events are written in the data layer and will be fired as soon the operation completed successfully. For more details see the CustomerAdded event in the file CustomerRepository.cs

Pros : All the events reside at a single place.So easy to maintain.ViewModels will contain only data bindable properties and commands.

Cons : If they data layer is done by some other developer who is in different location and doesn’t care about the MVVM this fails.If the project is just to upgrade the UI of an existing application to WPF, we can’t expect the existing data layer with these type of events.

Events at ViewModel level

Here the events are written in the view models.Whenever an operation finishes or a view model wants to notify other viewmodels about something, it will raise an event which in turn ,captured by other view models and they can process according to that.

In the attached sample showing the editing customer view is done by that method.The AllCustomersViewModel has got a new event called EditCustomer which is fired when ever the user clicks on the edit command.ie When we click on the Edit link in the AllCustomersView the event EditCusomer will get fired.Thus MainViewModel receives the notification since it has subscribed to that event and it shows the CustomerView with the selected customer.

I think there is no need to explain the pros and cons as it is reverse of the above.

2.Mediator pattern

This is a well known pattern.For more details about the pattern see these posts

MVVM Mediator Pattern

[MVVM + Mediator + ACB = cool WPF App] – Intro « C# Disciples

In the attached sample you can see the ViewModelMessages.CustomerDeleted message is dispatched  after the deletion in the method CustomerViewmodel.Delete().This is captured by the AllCustomersViewmodel and it updates its collection to update the view.

Sample

The sample attached here is taken from the famous MVVM article by Josh Smith.Thanks Josh.I modified that sample to show these notification mechanisms.It contains the implementation of all these messaging techniques mentioned above.Another change I did is creating separate projects for view,view-model,model,MVVM etc…to easily understand the separation of model and view.

The sample can be downloaded from here.

Monday, May 11, 2009

Writing custom TriggerAction using Interaction to enhance MVVM

The Blend team has introduced a new concept called Interactions for both WPF and Silverlight.According to my understanding it is a method to interact with the xaml elements without writing code behind.Expression Blend is developed using the new architectural concept MVVM and I think they mainly introduced it to enhance MVVM.

There are 2 methods to implement this interaction.One is Behaviors and other is Triggers.Behaviors will be covered in a separate post.This post is related with Triggers, Actions and creation of  a custom Action called FollowMouse.

I have already wrote a post about Microsoft.Expression.Interactivity.dll which tells about creating a custom trigger named RoutedEventTrigger which fires on the associated RoutedEvent.In that post, the intention was to invoke a command upon attached events like Mouse.MouseDown,Mouse.MouseMove,Contacts.ContactDown etc…That is too, very much useful to achieve a perfect MVVM architecture.

In the perfect MVVM world there should be no code behind for xaml files.But when we implement in the real world ,sometimes we will be forced to write code behind to implement some special cases such as MessageBox.Show.Using the Microsoft.Expression.Interactivity.dll we can write actions which display the messagebox.

More links about the behaviors and interactions are below

http://electricbeach.org/?p=147
http://blog.kirupa.com/?p=341

What are these new Interactions

As I told earlier this is a method to interact without writing code behind.The code will be encapsulated in the action classes.See the example below which shows  a MessageBox using only xaml upon a MouseDown.

<Grid Background="Red">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<myactions:ShowMessageBoxAction MessageBoxText="Mouse down" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Grid>


Hope the above code is clear.It tells to show a MessageBox upon MouseDown in the Grid.We know that it is not possible or don’t have default support in xaml to show the message itself.Then where is the C# code to show the message.The answer is simple.It is in the ShowMessageBoxAction class.That class has a MessageBoxText property which is displayed on invoking that action.


To implement interaction it is using attached properties.Interaction.Triggers is an attached property of type TriggerCollection.We can add as many triggers we want.The condition is that all those triggers should be derived from TriggerBase.Here I have used built in EventTrigger and a custom action ShowMessageBoxAction.


Developing our own custom Trigger Action : FollowMouseAction


Writing a custom trigger action is very simple.There should be a reference to the Microsoft.Expression.Interactivity.dll in our project.That dll is from Expression Blend 3 so it should be blend installed in your system to refer.Path is <Install drive>:\Program Files\Microsoft Expression\Blend 3 Preview\Libraries\WPF.Or you can download from any blogs.


The action class ,we need to derive from the base class named Microsoft.Expression.Interactivity.TargetedTriggerAction<T> this has a generic parameter which is the type of the target.


Here we are going to implement a FollowMouseAction.The purpose of this is to create an action which follows mouse and updates it’s position according to that.For that we have to associate trigger to a Canvas.Canvas is the simple panel in which children can be easily placed by specifying Left and Top.So at the time of inheriting class we have to specify the Canvas as it’s action type.


One more thing we need is which child of canvas is following the mouse.So we have to add one more property called Element which is of type FrameworkElement.On action invocation we will be setting the Canvas.Left and Canvas.Top properties of Element according to the mouse position.




public class FollowMouseAction : Microsoft.Expression.Interactivity.TargetedTriggerAction<Canvas>
{
public FrameworkElement Element
{
get { return (FrameworkElement)GetValue(ElementProperty); }
set { SetValue(ElementProperty, value); }
}

// Using a DependencyProperty as the backing store for element. This enables animation, styling, binding, etc...
public static readonly DependencyProperty ElementProperty =
DependencyProperty.Register("Element", typeof(FrameworkElement), typeof(FollowMouseAction), new UIPropertyMetadata(null));

protected override void Invoke(object parameter)
{
Point pt = Mouse.GetPosition(this.Target);
if (Element != null)
{
Element.SetValue(Canvas.LeftProperty, pt.X);
Element.SetValue(Canvas.TopProperty, pt.Y);
}
}
}

Using the FollowMouseAction in xaml.



<Grid>
<Canvas Width="300" Height="300" Background="Red">
<Ellipse Width="50"
Height="50"
Fill="Green"
x:Name="ele">
</Ellipse>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown">
<myactions:FollowMouseAction Element="{Binding ElementName=ele}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Canvas>
</Grid>


The above code updates mouse position when we click on the mouse.How can we make it movable accoring mouse ?Easy just change the event name to “MouseMove”.See below if you are still not clear.



<Grid>
<Canvas Width="300" Height="300" Background="Red">
<Ellipse Width="50"
Height="50"
Fill="Green"
x:Name="ele">
</Ellipse>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseMove">
<myactions:FollowMouseAction Element="{Binding ElementName=ele}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Canvas>
</Grid>



NB: Please don’t confuse these Triggers and Actions with the standard triggers and actions available in WPF.They are entirely different where the Triggers mentioned here comes from the namespace Microsoft.Expression.Interactivity and the standard WPF Triggers comes from System.Windows



The above is applicable to Silverlight too.The only change you have to to do is change the reference to the interactivity dll located at <install drive>:\Program Files\Microsoft Expression\Blend 3 Preview\Libraries\Silverlight.If you need more and more details please see this great article from my colleague Laurent Bugnion 


Sample can be downloaded from here.

Saturday, May 9, 2009

MVVM Developing a generic Mediator class

When I tried to separate the MVVM related classes to a different project called ‘MVVM.Core’ for future use,I came to see one issue.That is the mediator which I used is handling messages which are specific to my project.’GameOver’,’GameStarted’ etc…This would not be the case in my future projects.There the messages may be ‘UserAdded’,’UserDeleted’ or something else.So I decided to make the existing Mediator class generic.
The MultiDictionary remains the same as in MVVM Mediator Pattern(This is the place where I got Mediator code.Thanks to Sacha Barber).The changes are mainly in the Mediator class.I removed the ViewModelMessage enum (specific to my project)from that class and made it coming as generic type parameter T .Changed all references of ViewModelMessage into T.The below code snippets tell the difference.

public sealed class Mediator
{...}


public sealed class Mediator<T>
{...}

Then I had to change the view model hierarchy.I created a new Viewmodel which is called MediatorEnabledViewModel to contain the Mediator functionality.



public class MediatorEnabledViewModel<T>:WorkspaceViewModel
{
public Mediator<T> Mediator
{
get
{
return Mediator<T>.Instance;
}
}
}

These classes are in MVVM.Core project and in the application specific viewmodel project, I added one more base viewmodel which is more specific to the application where I specify the type of generic parameter T.



public class DemoAppViewModelBase : MediatorEnabledViewModel<ViewModelMessages>
{
public CustomerRepository CustomerRepository
{
get { return CustomerRepository.SingleTon; }
}
}

Now its all set.We can change the type of the message which mediator handles from the application’s view-model according to the nature of the application.Type of the message can be any enum which contains application specific values / messages.Below is the screenshot of solution structure.



The entire mediator code can be downloaded from here

Thursday, May 7, 2009

MVVM invoking command on attached event

When I started my last WPF project using MVVM by referring Josh Smith’s article ,I was very much excited about the way it separates the view and model.But after going some way, I got issues.The reason was how to execute command on events like MouseOver and MouseDown.In the sample which I got,the commands were  just bound to the Button.Command property.It was possible because the Button implements ICommandSource interface.In that case also we can’t invoke command on events other than Button.Click.

After a tough Google ,I found this article in Jaco Karsten’s blog which allows to invoke command on any control any event.The only thing is we have to use an Expression Blend 3 dll named Microsoft.Expression.Interactivity which have its own attached Interaction trigger mechanism along with Jaco’s CommandAction class.Attached trigger mechanism allows us to add a EventTrigger and CommandAction class will invoke a command when the trigger if fired.Life became cool again.Thanks to Jaco.

<Image Width="360"
Height="177"
Source="sample.jpg">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseMove">
<mvvmjaco:CommandAction Command="{Binding MouseMoveCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Image>

Implemention of Interaction.Triggers and Command action.Command will execute when the trigger fired


When this comes to Surface,I again saw a hurdle.We can’t invoke command on attached events.For example we can’t invoke command on s:Contacts.ContactDown.

After reflecting the class EventTrigger present in the Microsoft.Expression.Interactivity dll, I came to know that it is using reflection to find out the event from it’s EventName property which is not applicable in the case of attached events.Hence I was forced to create a new trigger which fires on attached event by inheriting EventTriggerBase<T> class.


Implementation of RoutedEventTrigger


A property named RoutedEvent of type RoutedEvent is being added.In the overridable method OnAttached, I attached a handler to the RoutedEvent and in the handler call the OnEvent method present in the base.That in turn calls all the actions associated with that trigger.For more details see the code below



public class RoutedEventTrigger :EventTriggerBase<DependencyObject>
{
RoutedEvent _routedEvent;

public RoutedEvent RoutedEvent
{
get { return _routedEvent; }
set { _routedEvent = value; }
}

public RoutedEventTrigger()
{
}
protected override void OnAttached()
{
Behavior behavior = base.AssociatedObject as Behavior;
FrameworkElement associatedElement = base.AssociatedObject as FrameworkElement;

if (behavior != null)
{
associatedElement = ((IAttachedObject)behavior).AssociatedObject as FrameworkElement;
}
if (associatedElement == null)
{
throw new ArgumentException("Routed Event trigger can only be associated to framework elements");
}
if (RoutedEvent != null)
{
associatedElement.AddHandler(RoutedEvent, new RoutedEventHandler(this.OnRoutedEvent));
}
}
void OnRoutedEvent(object sender,RoutedEventArgs args)
{
base.OnEvent(args);
}
protected override string GetEventName()
{
return RoutedEvent.Name;
}
}


Using RoutedEventTrigger



<Image Width="360" Height="177" Source="Resources\PlayerArea.png">
<i:Interaction.Triggers>
<mvvmjoy:RoutedEventTrigger RoutedEvent="s:Contacts.ContactDown">
<mvvmjaco:CommandAction Command="{Binding TouchCommand}" />
</mvvmjoy:RoutedEventTrigger>
</i:Interaction.Triggers>
</Image>




Executes touch command on Contacts.ContactDown event.

Friday, May 1, 2009

MVVM Resources

MVVM or M-V-VM is a new architecture like MVC and MVP ,which is more suitable for WPF and Silverlight which supports data binding .It stands for Model View ViewModel.Before reading further please have some idea in MVC (Model View Controller) and MVP(Model View Presenter) if you don’t have already.

Some links to MVC and MVP

MVC - The Official Microsoft ASP.NET Site
Design Patterns- Model View Presenter
Model View Presenter - Wikipedia, the free encyclopedia
http://www.codeproject.com/KB/architecture/ModelViewPresenter.aspx

What is M-V-VM

Model and View are same as in MVP and MVC.The only change is in the ViewModel. This effectively separates the model and view.Confused?Lets see what is this new View model ?

View model is a class which wraps data binding enabled view objects or properties and commands which drive the flow of the application.The properties contain what ever the view is supposed to display.These properties are designed based on the model.Commands are just WPF commands which implements the ICommand interface.They are executed by the user actions from the view.So they are normally associated with the buttons or other controls which implements ICommandSource interface.

Simply saying the view model loads the data which are to be displayed from model and displays through view by means of data binding.In the reverse direction it accepts user actions from view through commands and performs required actions on model.

In the ideal situation there should be no direct communication between view and the model.Everything should pass through the view-model.One more thing in ideal situation is views should not have a code behind.Have an image google using MVVM if you need a block diagram of this architecture.

Learning and designing MVVM architecture

Due to time limit ,here I am giving some links which describe MVVM in detail.Hope I can write more about implementation side later.At the first time you will feel that, this is very difficult to achieve.Scenarios such as ‘performing something on ListBox selection but it doesn't have a Command property which executes on selection’ and  ‘method to invoke a command on mouse over’ will come.But once you go through the below links you can find solutions for all these issues and go smoothly with MVVM.

Intro to MVVM by Josh Smith
THE MODEL-VIEW-VIEWMODEL (MVVM) DESIGN PATTERN FOR WPF

Using mediator pattern to implement communication among view models
[MVVM + Mediator + ACB = cool WPF App] – Intro « C# Disciples

Command invocation on any control any event
Applying Command Binding to any control and any event

Will be adding more as soon as I come across