jump to navigation

Building a simple application with Blend and Visual Studio April 26, 2009

Posted by fofo in general .net, Visual Studio 2008, WPF, XAML.
Tags: , , , ,
3 comments

I have dedicated lots of time recently to understand WPFapplications and the large WPF API.

I have been working with window forms applications for many years and I wanted to have a look at this rather new technology, which is a brand new way of building desktop and RIA applications.

There is a lot of stuff one must learn and along with WPF API and Visual Studio, Microsoft Blend is almost a necessity to explore and learn.

I will create a small application with Blend and Visual Studio in this post.

But I think it is very important to understand why Microsoft created WPF and the accompanying tools and what are the differences between WPF and Window forms applications.

Let’s start with the differences between WPF and Win forms

  1. Window forms was built on top of  2 lower APIs User and User 32(newest version) and GDI

WPF is built on top of DirectX. We could design-draw an application using User32 and GDI libraries but we could never do things like 3-D effects, transparency, shadows. We can do that with DirectX.WPF is relying on DirectX.User32 and GDI are rendered via the CPU.

DirectX utilises the GPU.Almost all PCs nowadays have integrated GPUs and with WPF we can harness that extra processing power.So it was natural for Microsoft to implement and provide us with an API , WPF in this case, to take advantage of the new capabilities of graphic cards.The WPF application when it starts it checks to see on what kind of machine it executes and decides if it needs to downgrade certain effects.

2. XAML is used to define the WPF objects and is built on top of WPF API. It is an XML-style language. Expression Blend is just a tool in assisting developers-designers in the creation of User Interfaces. Expression Blend generates XAML code. The business rules and the back end access is still  implemented with .Net languages

3. With WFP we have the addition of New Navigation Project types. In WPF we have the option to create page based applications. For example we can navigate back and forth in our application like in a web based interface.

4. The layout of the controls in WPF is quite different.WPF’s default layout is relative. In a WPF application it is much easier to resize and reposition controls

5. With WPF we have much better tools at our disposal when dealing with audio and video within our applications

6. We can have fantastic and really impressive animations in our WPF applications, somthing we could not really do easily with window forms.

7. We have “Themes and Skins” in WPF. It was very difficult in Window forms applications to keep all the controls (e.g buttons in all forms) to have the same background color.In WPF we can do that through styles and templates.

Let’s start building our first application using Blend and Visual Studio. I assume that you have Visual Studio 2008 installed.Visual Studio 2008 express editions can be downloaded from here. Download the Visual C#  2008 Express edition.

If you need to download Expression Blend 2.0 click here. Bear in mind, this is a trial software…

1) Launch Visual Studio 2008 and as a project template choose “WPF application”. Select C# as the labguage of development.

2) Save your project with a name e.g “myfirstWPFapp”

3) Launch Expression Blend 2. Open the “myfirstWPFapp” from Blend by clicking File->Open -> Project/Solution

4) Our solution is opened both from Visual Studio and Expression Blend. I will use Expression Blend to create the basic user interface. Drag and drop a button on the . You can resize it if you want, give it a name and set it a color. You can do all that from the Properties window. Spend some time to familiarise yourselves with the Blend IDE.

5) Click the “Window” option which is a top level menu in Blend.Check the “Interaction” option.The Interaction window is now visible.

6) Add a new event in the interaction window. When the button is clicked a new event is raised. You will see a message from Blend saying “No storyboard exists for you to begin or to control.One will be created.” Click OK

Have a look at the image below.blend

7) Now we have a new window appearing in our IDE, Objects and Timeline. Notice also that on the top left corner the statement “Timeline recording is on” is written.

8) From the “Objects and Timeline” window-pane drag a line(yellow line) until you reach 1.5 seconds in time in order to create a timeline

9) Now select the corner of the button and try to flip-rotate it 180 degrees.It is very easy to do. Just select the button and wait until the curly double-head arrows appear.Then just rotate it.

10) Now add another 1.5 seconds in the timeline, by dragging the yellow line to the 3 seconds interval. Rotate the button back to its original position.

11) Hit F5 to run your application. Click on the button to see that rotates

12) Close Expression Blend. Switch to Visual Studio. Reload and click “Yes” when asked to save the solution.

13) Run your application from Visual studio by hitting F5. You see the same results.

14) Double click on the button. In the code behind file in the event handler subroutine, simply type

MessageBox.Show(“This is a first WPF application”);

15) Run your application again. When you click your button, first the message pops us and then the animation starts to unfold.

So in a much more complex application than this, the designer can create the UI and the stunning effects while the developer can concentrate on the business rules and the data access.

Finally it is worth pointing out that

1) We can have  Windows Presentation Foundation inside existing Win32 code and vice versa we can have existing Win32 code inside Windows Presentation Foundation

2) WPF is interoperable with Window forms  through the use of the ElementHost and WindowsFormsHost classes.

And remember that Window forms are here to stay despite all the things I have been pointing out in this post.As things stand now, most users are familiar with the “look and feel” of window forms and there are more third party tools-components for window forms.

WPF is a new way of delivering excellent functionality with more style!!!!!!!!!

Hope it helps!!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Create a simple data-centric WPF application March 28, 2009

Posted by fofo in VB 9.0, Visual Studio 2008, WPF, XAML.
Tags: , , ,
8 comments

I have been asked from some people to write a simple post regarding the younger and more flashy brother of  window forms. WPF is about 1 years old now and gaining ground on developers for building next generation window applications. I urge people who are new to WPF to familiarise themselves a little bit with WPF by clicking here .

In this post I am going to do just that through a very practical hands-on example. I am going to use Visual Studio and VB 2008 to build a simple data entry form.

I am going to use the Northwind database as our data store for this example.

Click here to download the installation scripts. Fire SQL Server 2005/2008 Express Edition or SQL Server Standand edition 2005/2008 and run the scripts. All the tables and their related data is now available for us to use.

1) Launch Visual Studio 2008 professional or express edition

2) Create a new project by choosing from the available templates WPF application (choose VB as your language of development)

3) Name your application myfirstWPFapp.

4) Click the Data from the menu and then click Show Data Sources.Click on the Add New Data Source link.

5) Select Database from the Dialog window and click Next .

6) Create a new connection string by clicking the New Connection. In the new window that appears choose the SQL Server name to connect to. This is of course the server that you installed the Northwind database. In my case it is FOFO-PC\SQLEXPRESS and then select the database from the dropdown list (Northwind of course). Test the connection and click OK to close the window.

7) CLick Next on the data source configuration wizard and save the connection string as NorthwindConnectionString. Click Next.

8) In the next step of the wizard from all the database objects expand the table node and select Customers. Name the dataset CustomersDataset. Click Finish.

9) In the Window1.xaml just drag and drop 4 button(on the right hand corner) controls from the Toolbox on your Wpf form. We want to add, delete,save and cancel(cancel the data that we are currently inserting) data from our Customers table. Name the buttons accordingly by changing their Name property for each one of them. I named them for example btnSave,btnCancel, e.t.c.Give them an appropriate label by changing  the Content property for each one of them.Change from the properties window some properties e.g background,foreground colors. Align the buttons and make them the same width. This is a good practice.These changes will be saved in the XAML code that you can see in the lower half of the window. We will not focus too much on the design issues in this post.

10) Drag and drop 7 label controls on the WPF form. Name them e.g lblCustomerID,lblCompanyname lblName,lblCity,lblCountry,lblRegion,lblPhone. Give them an appropriate text by changing  the Content property for each one of them.Change from the properties window some properties e.g background,foreground colors. Align them and make them the same width by setting the width property for each one of them to “100″.

11) Drag and drop 5 textboxes on the Wpf form.Name them e.g txtCustomerID, txtCompanyName,txtName,txtCity,txtCountry,txtRegion,txtPhone. Change from the properties window some properties e.g background,foreground colors. Align them and make them the same width by setting the width property for each one of them. Align the label controls and the textbox controls using the visual alignment controls. Resize the formif you want.

12) We have not finished yet. We must provide some sort of navigation controls to our application. In WPF applications we do not have ready controls(navigators) like we did with normal window forms. Drag and drop 4 button(on the left hand corner) controls from the Toolbox on your Wpf form. We want to allow users to navigate to the first,last,previous and next record from our Customers table. Name the buttons accordingly by changing their Name property for each one of them. I named them for example btnfirst,btnlast, e.t.c.Give them an appropriate label by changing  the Content property for each one of them.Change from the properties window some properties e.g background,foreground colors if you want. Align the buttons and make them the same width.If you have followed along every step you must have something similar with this picture below

wpf-new-1

13) That seemed like a lot of work… Ok, so now we are ready to finally do our databinding tasks. We obviously need to populate the textbox controls with data from our Customer database table through our CustomersDataSet object and the Customers Data Table object.If you have done databinding using window forms , you may think that we simply drag and drop the fields from the Data Sources window on the wpf form. We can not do that. But we can databind the textboxes to their respective values from the database from XAML code. We do that by telling each textbox Text property that is bound to the relevant field in the table. In the XAML pane we locate the first textbox, and we bind it to the CustomerID field using this code(i just typed the code in brown color):

<TextBox Grid.Column=”1″ Grid.Row=”1″ Height=”23″ Margin=”61,13,103,0″ Name=”txtCustomerID” VerticalAlignment=”Top” Text=”{Binding Path=CustomerID}” />

You do that for the remaining 6 textbox controls.

14) Now we need to load the data in our form. We must write some code in our code behind file in the appropriate event. This is the Window_Loaded event handler routine. We must create some variables for our dataset,tableadapter and tableadaptermanager. You can do this by writing something like that

Dim customerdataset As New CustomersDataSet

Dim customeradapter As New CustomersDataSetTableAdapters.CustomersTableAdapter

Dim customermanager As New CustomersDataSetTableAdapters.TableAdapterManager

Now inside the event handling routine you have

Private Sub myfirstWPFAPP_Loaded(ByVal sender As Object, ByVal e As    System.Windows.RoutedEventArgs) Handles Me.Loaded

Me.customeradapter.Fill(Me.customerdataset.Customers)

Me.DataContext = Me.customerdataset.Customers

End Sub

15) If you hit F5 and run your application you will see the first row(only the fields we specified, not all of them) of the Customers Table loaded into the 7 textboxes. That is great!!! But we do not need just the data for one record, we need all the records. For this we need to write some code in our navigation controls. In order to do that we need an object to navigate the data collection. This object is the CollectionView object.

We create a variable of that data type e.g

Dim myview As CollectionView

and inside the form Loaded Event(myfirstWPFAPP_Loaded)we type the following line to give a value to our object

Me.myview = CollectionViewSource.GetDefaultView(Me.customerdataset.Customers)

16) Double Click the button that you named “First”. An event handling routine is created. Add this line of code

Me.myview.MoveCurrentToFirst()

So the full code is:

Private Sub btnfirst_Click(ByVal sender As System.Object, ByVal e As  System.Windows.RoutedEventArgs) Handles btnfirst.Click

Me.myview.MoveCurrentToFirst()

End Sub

17) Double Click the button that you named “Previous”. An event handling routine is created. Add these three lines of code inside it. In this case we check with a very simple If statenement if we are on the first record. If not we can go to the previous one.

If Me.myview.CurrentPosition > 0 Then

Me.myview.MoveCurrentToPrevious()

End If

18) Double Click the button that you named “Next”. An event handling routine is created. Add these three lines of code inside it. Here we check if we are in the last row of our table. If not , we move to the next record.

If Me.myview.CurrentPosition < Me.myview.Count – 1 Then

Me.myview.MoveCurrentToNext()

End If

19) Double Click the button that you named “Last”. An event handling routine is created. Add this line of code inside it.

Me.myview.MoveCurrentToLast()

20) Run your application by hitting F5. Make sure that the navigation buttons operate as desired.

21) Yes it is now time to write some more code so our ,cancel,save,delete,add buttons to be operational.Double Click on the “Delete” button on your form. An event handling routine is created. Add these 4 lines of code inside it.

If Me.myview.CurrentPosition > -1 Then
Dim row = CType(Me.myview.CurrentItem, System.Data.DataRowView).Row
row.Delete()

End If

We check to see that we are in a record and that our table is not empty. Then we must get the row that is currently in view and then we simply delete it. I want to highlight something here. This Customers table is related via a foreign key constraint to the Orders table which is another table of the Northwind database. If you go to delete one record from the Customers table that has placed an order, then you will receive an error. In order to test the “Delete” button just add a brand new customer using the “Add” button first.

22) Double Click on the “Add” button on your form. An event handling routine is created. Add these 3 lines of code inside it.

Dim row = Me.customerdataset.Customers.NewCustomersRow

‘ because these fields do not allow nulls we specify some values

row.CustomerID = “[mid]“
row.CompanyName = “[my company name]“

Me.customerdataset.Customers.AddCustomersRow(row)

Me.myview.MoveCurrentToLast()

23) Double Click on the “Cancel” button on your form. An event handling routine is created. Add this line of code inside it.

Me.customerdataset.RejectChanges()

24) Double Click on the “Save” button on your form. An event handling routine is created. Add these 7 lines of code inside it.

Try
If Me.customerdataset.HasChanges Then

Me.customeradapter.Update(Me.customerdataset)

End If

Catch ex As Exception
MsgBox(ex.Message)

End Try

25)  Run your application. Add a new customer by clicking the “Add” Button and filling in the data and click the “Save” button. A new customer is in the database. Then click the “Delete” Button while the newly created customer row is active. Click the “Save’ button again.The customer is deleted. Check these changes in your actual database.

Hope it helps. If you need the source code email me at nkantzelis@q-training.gr

Happy browsing!!!!

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

Follow

Get every new post delivered to your Inbox.

Join 1,787 other followers