Teach Yourself WPF in 24 hours (Hour 3)

Source: Internet
Author: User
Tags microsoft outlook

Recently, as the project needs to start learning the legendary WPF, er, Spring brother seems to be a little angry with me. I haven't found it for a long time when I used Google to find learning materials. Later I found a book on the computer about WPF that I don't know when to download, that is, the one I want to translate.

This book has two purposes: 1. Learning WPF and completing projects

2. I haven't moved bird for a long time. I don't know if I can do it. Let's take a look.

Since it is not a senior bird expert and WPF is also a newbie, you may be right about the translation. Well, let's rock.

Er, there is a bit of nonsense. The first two hours in this book are some introductions to WPF. I will not bother to translate them, but I will go straight to the third hour.

Third-hour Font viewer Introduction

(It is actually a Font viewer)

What will you learn in this hour:

How to create a new WPF Project

Some basic knowledge of

Ø structure of a WPF Project

Ø XAML File

Ø background code file

In this hour's course we will build the first WPF Application-an auxiliary tool to view all fonts currently installed in your system. We will also learn how to create a simple WPF project in Visual Studio.

Create a Font viewer

Let's talk about the application we will build to start this course.

It is very convenient to have a lightweight auxiliary tool that allows you to view the fonts installed in your current system. In addition, we can enter some sample text to see how it works in the current font.

To complete this auxiliary tool, we need:

A ListBox is used to display all fonts installed in the current system.

Enter the sample text using a textbox.

A place where the sample text can be displayed in the selected font

Create a new project in Visual Studio 2008

We will be developing in Microsoft Visual C #2008 express edition (see Figure 3.1. This is a special version of Visual Studio released together with. net3.5. It supports the development of WPF programs. If you have other versions of vs2008, it is also feasible. Of course, your steps may be slightly different from this book.

The procedure for creating a WPF project is as follows:

1. Open Visual Studio. It is in your Start Menu.

2. Select File-new project in the menu bar.

3. Select the WPF application template, as shown in Figure 3.2.

4. Name your application fontviewer and click OK.

(How do I feel like the author treats readers as idiots... Those who want to learn WPF should have these foundations)

       
 
 
   

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Figure 3.1 Microsoft Visual C #2008 express Edition

 

 

 

 

 

 

 

 

Figure 3.2 Create a New WPF Application

Basic engineering documents

Vs will automatically create app. XAML, window1.xaml, and background code files associated with window1.xaml, and then window1.xaml will be displayed in your ide.

The XAML file contains only some of the markup we discussed in the second hour-Understanding XAML. The background code file contains some additional code associated with the XAML (in this example, the C # code ).

App. XAML represents the application itself. It is not visualized and mainly used to save the resources used by the entire application. App. XAML also defines the form opened when the application is loaded.

Window1.xaml is the main form of the entire program. The tag contains all the visual elements of the application and declares the behavior of the program.

What is background code?

In a WPF application, each XAML file has a corresponding background code file. The background code file and its parent file have the same name and are suffixed with. CS or. VB. Therefore, the background code file of window1.xaml is window1.xaml. CS.

In the solution browser, the background code file is the child of the file associated with it (tree structure display ). They are nested under the parent file.

You can right-click the code editor and choose view code or view designer to switch between the markup language and code. Note that Vs will open a label for both the XAML and the background code.

Remove your concerns

The purpose of using background code files is to enable developers to separate UI rendering development from program behavior development and focus on their respective development work. In practice, WPF is better than Windows Forms and ASP. NET web forms, although this makes it easy for us to confuse these things. (Original sentence: although it is still very easy to muddy the waters. I don't know how to turn it over, ER .)

For example, assume that a team of two people is developing a WPF application, one of which is an artist and the other is a code Engineer (haha, this translates my voice-it's all migrant workers ). The Code Engineer wants to implement a function that allows users to select their favorite colors in a ListBox. The artist wants to use a color palette to display the colors selected by the user in The ListBox. In this case, the artist can edit the XAML file to create a unique ListBox without changing the code written by any coders and without damaging the entire application.

This is just the tip of the iceberg that separates the uidesign from the behavior logic. In this book, we will discuss more about this concept and the benefits of doing so.

Rename a XAML File

The Font viewer application we just created is now opened in. If you press F5, you will see a WPF application that can run but is useless.

The default vs file name does not make much sense. Naming objects, classes, and methods based on their purposes is a good habit. Therefore, we will rename window1.xaml to indicate that it is the main form of the entire program.

If you are not careful, renaming items in Vs will destroy the entire application. To ensure the correct association between files when renaming a form, we need to do this:

1. Select window1.xaml in the solution browser.

2. Press F2 (similarly, you can right-click and choose rename ).

3. Rename window1.xaml to mainwindow. XAML. At this time, we will notice that vs automatically renamed the associated background code file. However, vs does not correctly rereference the new file name or change the name of the internal class.

4. Double-click app. XAML in solution manager to open it in the editor.

5. The root tag of APP. XAML is the application tag, and the application tag has an attribute named startupuri. The startupuri attribute specifies the main form displayed when the application is running. We can see that it also points to the old file name window1.xaml. Now let's change it to mainwindow. XAML. The modified app. XAML looks like this:

<Application X: class = "fontviewer. app"

Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"

Startupuri = "mainwindow. XAML">

<Application. Resources>

</Application. Resources>

</Application>

6. Open the background code of mainwindow. XAML in the Code Editor, that is, mainwindow. XAML. CS. We noticed that the class is still window1. renaming the XAML file does not change the class name.

7. To avoid confusion, we should change the class name to match the file name. Right-click the class name, select rebuild-Rename, enter mainwindow as the new class name, click OK, and then click application. You can also choose refactoring in the menu sample-Rename 3.3.

We will also notice that vs does not correct the class name in the comment before the class, so we also change the class name in the annotation -- it is a good habit to ensure that the annotation is updated synchronously with your code.

8. Finally, in the tag of the mainwindow. XAML file, we also need to change the referenced class to the correct class. The root tag of the markup language is window, which has an attribute X: class. Change this attribute to the full name of the class, including the namespace, fontviewer. mainwindow. mainwindow. XAML. After the correction, mainwindow. XAML looks like this:

<Window X: class = "fontviewer. mainwindow"

Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"

Title = "Font viewer"

Height = "300"

Width = "300">

<Grid>

</GRID>

</WINDOW>

 
 

Figure 3.3 select refactoring in the menu bar

 

 

 

 

 

 

 

Develop this application

At the beginning of the course this hour, we said what we were going to do -- use our applications to display the security of the current system

List of all fonts installed. We also want the program to have this function: select a font in a list, and enter some sample text in the text box to see the effects of the text in the font.

It is also very important to make a program easier to use, so we will also add some useful prompt text and intervals in the program to improve the availability of the program.

Now, let's add these features:

1. Open mainwindow. XAML in the code editor. By default, vs uses a split form to display the XAML file. The design View pane in the form displays the preview effect of the xaml file in almost real time, while the XAML pane displays the markup language itself.

2. First, let's give the application a meaningful name, which will be displayed in the application title bar. Change the title attribute of the window label to Font viewer.

3. The default size of the form is too small. We can use the height and width attributes of the window label to change the size of the form. Set height to 480 and width to 600. (Unit: Px)

4. Now go to the grid label. The grid control is one of the controls that allow you to visually arrange UI elements. These widgets for layout are called panels-we will discuss them in detail in the fourth hour of the course "Mastering the application layout. Delete the grid tag.

5. Enter <dockpanel where the grid is deleted just now. The smart sensing function will appear at this time. You can simply select the dockpanel from the list that appears. (Remember, use the <symbol to start the label when using the smart sensing function to enter the XAML tag. Dockpanel is another panel control similar to grid used to layout UI elements. Dockpanel is useful when you deploy applications like Vs and Microsoft Outlook-most of their UI elements are docked on the edge of the main form. The changed XAML should be like this:

<Window X: class = "fontviewer. mainwindow"

Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"

Title = "Font viewer" Height = "480" width = "600">

<Dockpanel> </dockpanel>

</WINDOW>

6. Enter the following code in the dockpanel:

<Border dockpanel. Dock = "TOP"

Cornerradius = "6"

Borderthickness = "1"

Borderbrush = "gray"

Background = "lightgray"

Padding = "8"

Margin = "0 0 0 8">

</Border>

In the design view, we can see that the application's main form now contains a light gray rectangle with rounded corners. Remember to look at the design view from time to time when editing the XAML file so that you can better understand the markup you are entering-they are all displayed in the design form in real time.

7. It is always useful to give your users some guidance. So, let's add some descriptive text. Enter the following content in the newly added border:

<Textblock fontsize = "14"

Textwrapping = "Wrap">

Select a font to view from the list below.

You can change the text by typing in the region at the bottom.

</Textblock>

8. Now we will add a ListBox that displays all fonts currently installed by the system to the form. Add the following content after the border label (but still inside the dockpanel label:

<ListBox X: Name = "fontlist"

Dockpanel. Dock = "left"

Itemssource = "{X: static fonts. systemfontfamilies }"

Width = "160"/>

The itemssource attribute tells ListBox the data source to be displayed. In this example, the data we want to display is all fonts installed on the current system .. The class system. Windows. Media. fonts in the Net Framework provides a static attribute systemfontfamilies. By default, ListBox calls the tostring method of each fontfamily instance in the systemfontfamilies set. Fortunately, this method returns the name of fontfamily.

We will further discuss these details in the next course.

After completing the above steps, the markup language in mainwindow. XAML should be like this:

<Window X: class = "fontviewer. mainwindow"

Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"

Title = "Font viewer" Height = "480" width = "600">

<Dockpanel>

<Border dockpanel. Dock = "TOP" cornerradius = "6" borderthickness = "1"

Borderbrush = "gray" background = "lightgray" padding = "8" margin = "0 0 0 8">

<Textblock fontsize = "14" textwrapping = "Wrap">

Select a font to view from the list below.

You can change the text by typing in the region at the bottom.

</Textblock>

</Border>

<ListBox X: Name = "fontlist" dockpanel. Dock = "Left" itemssource = "{X: static fonts. systemfontfamilies}" width = "160"/>

</Dockpanel>

</WINDOW>

9. Now we need some methods to enter the sample text and use the selected font to preview the text.

Add the following tags under ListBox:

<Textbox X: Name = "sampletext" dockpanel. dock = "bottom" minlines = "4" margin = "8 0" textwrapping = "Wrap" tooltip = "type here to change the preview text. ">

The quick brown fox jumps over the lazy dog.

</Textbox>

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "textwrapping =" Wrap "margin =" 0 0 0 4 "/>

Textbox accepts user input and provides some default text. Textblock is an element used to display text.

We noticed that the text attribute of textblock is bound to the text attribute of Textbox (named sampletext. This tells WPF to keep these two attributes synchronized-no matter when the user enters the text textblock In the textbox, it will automatically update to keep the content in the textbox the same.

10. Finally, run your program. Of course, you can also make some modifications to the program to experience the more charm of WPF.

Complete some details

After playing with the current Font viewer for a while, you can easily find that using a variety of fonts of different sizes to display the sample text will make the program more useful. Let's add some labels to display the sample text in the size of 10pt, 16pt, 24pt, and 32pt respectively.

We will make the following changes to display the sample text in different sizes in four different places.

1. Replace the textblock bound to sampletext with the following markup language:

<Stackpanel margin = "8 0 8 8">

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 10 "textwrapping =" Wrap "margin =" 0 0 0 4 "/>

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 16 "textwrapping =" Wrap "margin =" 0 0 0 4 "/>

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 24 "textwrapping =" Wrap "margin =" 0 0 0 4 "/>

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 32 "textwrapping =" Wrap "/>

</Stackpanel>

This adds a stackpanel in the program-another layout control. The stackpanel control stacks its child elements one by one. In this example, its child elements are four textbolck elements of different font sizes.

We noticed that all four textbolck instances are bound to the text attribute of the textbox named sqmpletext of the same data source.

2. Add an 8-pixel margin to the dockpanel. This makes the user interface look less crowded and increases the ease of use of the program:

<Dockpanel margin = "8">

The mainwindow. XAML after completion should look similar to the code listing 3.1.

Code List 3.1 mainwindow. XAML

<Window X: class = "fontviewer. mainwindow2"

Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"

Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"

Title = "Font viewer" Height = "480" width = "640">

<Dockpanel margin = "8">

<Border dockpanel. dock = "TOP" cornerradius = "6" borderthickness = "1" borderbrush = "gray" background = "lightgray" padding = "8" margin = "0 0 0 8">

<Textblock fontsize = "14" textwrapping = "Wrap">

Select a font to view from the list below.

You can change the text by typing in the region at the bottom.

</Textblock>

</Border>

<ListBox X: Name = "fontlist" dockpanel. Dock = "Left" itemssource = "{X: static fonts. systemfontfamilies}" width = "160"/>

<Textbox X: Name = "sampletext" dockpanel. Dock = "bottom" minlines = "4" margin = "8 0" textwrapping = "Wrap"

Tooltip = "type here to change the preview text.">

The quick brown fox jumps over the lazy dog.

</Textbox>

<Stackpanel margin = "8 0 8 8">

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 10 "textwrapping =" Wrap "margin =" 0 0 0 4 "/>

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 16 "textwrapping =" Wrap "margin =" 0 0 0 4 "/>

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 24 "textwrapping =" Wrap "margin =" 0 0 0 4 "/>

<Textblock text = "{binding elementname = sampletext, Path = text}" fontfamily = "{binding elementname = fontlist, path = selecteditem} "fontsize =" 32 "textwrapping =" Wrap "/>

</Stackpanel>

</Dockpanel>

</WINDOW>

 
 

 

Figure 3.4 Effect of running the first WPF Application

Have you noticed? Now our program has all the features we listed at the beginning of this course and can run correctly, but we didn't write a line of code.

If we can do this, what is the role of background code? We did not write any code!

In fact, we intentionally started learning WPF with a very simple application. When the problem we want to solve becomes more complex, it is necessary to compile the background code. However, this proves a powerful feature of WPF: You can do many things without writing any code!

Summary

In this hour's course, we talked about how to build a new WPF project, and then we built our first WPF Application: Font viewer. We also discussed the differences between the XAML file and the background code file. Finally, we demonstrated some impressive features of WPF at a higher level-data binding, layout, and Declarative Programming.

Q &

Q. Which files are automatically added to the WPF project?

A. App. XAML, window1.xaml, and their background code files. The former (App. XAML) indicates the entire application, and the latter (window1.xaml) indicates the main form of the application.

Q: What is the difference between a XAML file and a background code file?

A. the content in the XAML file is the markup language, while the background code file is associated with the XAML file. The content contains the code (such as C # code or VB Code)

Q. When you rename the XAML file in Vs, is the associated background code file affected?

A: Yes. The back-end code file is also renamed, but the class name has not changed. Therefore, if you want to keep the class name synchronized with the file name, you must manually change the class name.

 

 

 

 

This is the result of switching from word. We are sorry for this. please correct me if there are any errors.

 

This site uses the co-creation license signature, which is not for commercial purposes. For reprinting, please indicate the source and include the statement in this section. Cat_lee @ cnblogs

The translation of this series of articles has not been approved by the original author and is only used for learning and exchange. If you want to use this series of articles for other purposes, please be careful. I am not liable for any legal liability.

Finish whatever u've started !!!

My articles will be published in the blog. If you are interested, you can access cat_lee @ cnblogs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.