Can Of Code

Tag Archives: WPF

Understanding MVVM using MVVM Light

I had come across MVVM a number of times in my WPF travels but only in the form of the letters on a screen, so like any budding software engineer i decided to investigate.

WTF IS MVVM?

This question is where i started and it was a question i struggled with,  It seams that most people who write about MVVM are unable to explaining it such a manor that simple folk like myself can understand. Here is what i understood after reading a number of explanations.

Its a method of designing software so that you can easily separate the layout from the data. Separating the data makes testing easier and allows you to see test data when designing your layout in tools like Expression Blend.

The letters do actually mean something:

Description of View, View-Model and Model of MVVM

M = Model

This refers to your classes that define your OO business objects, for example your Customer class with the customers properties like customer name etc. Nothing new here!

V = View

The view is very much your XAML code and that’s it! The view is your Window. each new window is a view.

VM = View Model

The view model is the bit that is perhaps more confusing. The view model loads your data using your model and then using bindings lets your view use that data for the user interface. The View Model is where your load in your data from the database and load it into BO defined in your Model.

 

The order of the letters of MVVM i find disjointed. if it was up to me (for many reasons its not) i believe it should be View View-Model Model or VVMM, doesn’t have the same ring does it?

That’s Wonderful dear, But where on earth do i start?

Well word on the street has it that, doing things MVVM style adds more code to the proceedings, but.. before you hit the back button, someone has already done the hard work for you! This comes in the form of MVVM Light. You can download MVVM Light as an installer (Install MVVM Light). MVVM Light consists of a small framework that just takes out some of the hard graft, so i am told. Once installed all you have to do is create a new project using one of the freshly installed templates within VS2010.

This MVVM Light, What do i do with it?

To get started with MVVM Light,  i recommend that you go to the MVVM Light site which have a few tutorials to get you going. The most useful i found was the video explaining MVVM and MVVM Light and also a nice simple tutorial can be found here.

I’m still getting used to MVVM Light so i shall likely have some more posts on it soon.

Posted in Software, WPF | Tagged , , | 1 Comment

Some Simple WPF Tips and Tricks

Today its been raining all day, so its been the perfect excuse to do some more WPF practice. Below i compiled a small list of rather useful snippets of WPF related code which have helped me out.

1. Closing all other WPF Windows when closing a main window

Normally in an application your have a main WPF window that does some essential functionality. An example could be your web browser. The browser window is the main window and you may have an extra window which you can manage your bookmarks.

A quick and easy way i found to do this was create an event handler for the “Closing” event for the main window:

Closing="Window_Closing"

 

In the event handler we do this:

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
       foreach (Window win in App.Current.Windows)
       {
            if (win != this)
            {
                 win.Close();
            }
       }
}

 

The real gem here is the App.Current.Windows collection, which does what it says on the tin and has a collection of all the windows that have been created in your application. An important part of the snippet above is that we make sure to not close the Window that the code belongs to otherwise you get an Exception, trust me i tried it!

2.  Open an Existing instance of a WPF Window instead of a new Instance

Picture the scene, your creating an address book application and to add a new contact you have set it to bring up a new Add Contact Window. Once you finish you WPF application and release it out in the wild you get a angry email from Timmy, a frustrated user. For some reason hes got 53 instances of the Add Contact Window open!

Now to keep poor Timmy happy what you need to do is before opening a new instance of your WPF Window you want to make sure that none are already open.

And using the same magic as above you do the following:

foreach(Window win in App.Current.Windows)
{
    if (win.GetType() == typeof(propertiesWindow))
    {
        win.Show();
        win.Focus();
        return;
    }
}

 

What we are doing is looping through the collection of WPF Windows within your application and then checking if any of the windows are of the type we are wanting to open. If it does find one with the same type it will show the Window to the screen, if not it will do nothing.

To quote “Simples”.

3. WPF Visibility Property

Before i started learning the wonders of WPF, i worked with WinForms. With WinForms, life was simple, a Form or Component was either Visible = true or Visible = false. Along comes WPF stomping all over WinForms and worst of all forcing its three states of visibility on us!

After i found out what that third state was, i was willing to forgive WPF because its pretty handy. the third state is:

usrAddBtn.Visibility = System.Windows.Visibility.Collapsed;

 

Collapsed makes the WPF Element not only invisible but doesn’t reserve the space within the Parent Element. What does this mean in the real world? well it means that you could collapse a Panel and place a new Panel in its placed. This means that instead of creating new WPF Windows for settings pages for example,  you can reuse the space of your main Window.

Posted in c#, Software, WPF | Tagged , , , , | 1 Comment

WPF / C# notifcations pop up

There becomes a point in a lot of applications where you hit the notification wall. I have recently been working on an RSS Reader to practice some concepts that are covered in the MCTS (Windows Application Development 70-511) exam.  I got the application working with data bindings and all the other WPF Wizardry and decided to start using it. I currently use Outlook to read RSS Feeds so i thought it would be worth seeing if what i had created was any better.  I stumbled across a real issue for me. It didn’t notify me when it had updated. This isn’t really a big issue is it? Well it really was, because i have become very much hooked to applications telling me when something has happened for example, email, tweetdeck, MSN Messenger etc. Like below.

TweetDeck Notification window

A prime example of a notification window

 

Rather then give up with my application i thought why not add my own notifications to it! So here is a little guide on how to add a notification popup to your application.

 

the form

No massive surprise, but we start by creating a form or should i say window as its WPF. the window will be what is displayed when the notification happens.

Heres the one i made:

WPF Notification Popup

The design i can leave to your imagination, but there are a few properties within the window we need to set to make it look right. Here is the XAML snippet for window

<Window x:Class="RSSBuddy.notificationWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="notificationWindow"  ResizeMode="NoResize" ShowInTaskbar="False"
        Topmost="True" WindowStyle="None" HorizontalAlignment="Right"
        VerticalAlignment="Bottom">

 

So lets explain some of the things we are doing:

ResizeMode = NoResize

This is a pretty simple one, it just means the user wont be able to resize the notification window, which is fine because why would they want to?

ShowInTaskbar = False

Again, pretty simple, we don’t want this window to have an icon in the taskbar because its not really a window people will see for long.

Topmost = True

This property is pretty important to our notification window. the property forces the window right to the front of the screen in front of any open applications. If we didn’t set this to true, the notification window will end up getting lost behind other applications.

WindowStyle = none

This property means that we don’t have the border around the window or the close button and title. We set this to none so we can do our own title bar that fits better to the application.
HorizontalAlignment= Right & VerticalAlignment= Bottom

Both these properties are in charge of placing the window in the bottom right corner.

 Wait a minute…

If you now create your notification window and run it, something rather bizarre will happen. Your notification window will appear not in the very bottom right of the screen where you wanted it. This happens because it positions itself at the bottom right of its parent window NOT the screen. The way i overcome this was to do a bit of code tweaking before i opened the window:

  note = new notificationWindow(newitemcount);
  note.Top = main.ActualHeight - note.Height - 15;
  note.Left = main.ActualWidth - note.Width - 30;
  note.Show();

 

This code is what i use to open the notification window when something has happened. firstly we create the notification window object. Now to get over the problem of the misplacement. I go and manually set the notification windows Top and Left Properties. I set them by getting my parent screens ActualHeight (my parent screen is set to Maximise by default) and taking away the Height of my notification window and then and extra 15 for good measure. This results in the notification window appearing where it should!  the bottom right corner.

NOTE: If your parent screen is not Maximized you could use the following instead of the parent windows ActualHeight and ActualWidth (thanks to: this)

System.Windows.SystemParameters.PrimaryScreenWidth
System.Windows.SystemParameters.PrimaryScreenHeight

 

Posted in c#, Software, WPF | Tagged , , , | 3 Comments