WPF programming Basics

Source: Internet
Author: User

 

Development Preparation WPF programming is an innovative technology launched by Microsoft to break the Old Gui programming model. Windows Presentation Foundation. Visual Studio 2008 team system is recommended for development tools. C # is recommended #. WPF makes it easier to develop more beautiful interfaces, and it can better separate GUI Design from program logic than before, this allows qualified companies to specifically train graphic designers for GUI Design (a bit similar to Web art), while programmers focus more on business logic.

A simple example is used to create a WPF project named demo.

Pay attention to the gray area in the figure. It is a XAML file. If you do not use the vs2008 graphical design tool to write a XAML file, you can also design a GUI. It is very important to understand some basic knowledge of XAML, but we recommend that you use graphical design tools to work. After all, everyone wants to relax.

After the project is created, a window application is created. Now there is only one window. The window title is window1. The running result is as follows:

Understand XAML

XAML is fully called eXtensible Application Markup Language. XAML can be used to write WPF, but it can also do many other things. Each WPF program has an application object, which represents the entire application. It always has a static main method. There are multiple ways to compile an application class, refer to the http://www.cnblogs.com/kuku/archive/2007/02/09/645623.html

. However, this article was written earlier, and the latest vs2008 has some changes. The content of APP. XAML is as follows:

<Application X: class = "demo. app"

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

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

Startupuri = "window1.xaml">

<Application. Resources>

</Application. Resources>

</Application>

The value of the X: Class Attribute of the application element is the class app in the demo namespace. This class is defined as follows:

Using system;

Using system. Collections. Generic;

Using system. configuration;

Using system. Data;

Using system. LINQ;

Using system. windows;

Namespace demo

{

///

/// Interaction logic for app. XAML

///

Public partial class app: Application

{

}

}

We do not need to write the static main method. It is estimated that the compiler has generated it for us. The application element in APP. XAML also has a property startupuri that specifies the first window window1 displayed when the application starts running. The content of the window1.xaml file is as follows:

<Window X: class = "demo. window1"

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

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

Title = "window1" Height = "300" width = "300">

<Grid>

</GRID>

</WINDOW>

This should be easy to understand. Besides specifying demo. window1 as the window class, the value of the title, height, width attribute is also specified. The window1 class code is as follows:

Using system;

Using system. Collections. Generic;

Using system. LINQ;

Using system. text;

Using system. windows;

Using system. Windows. controls;

Using system. Windows. Data;

Using system. Windows. documents;

Using system. Windows. input;

Using system. Windows. Media;

Using system. Windows. Media. imaging;

Using system. Windows. Navigation;

Using system. Windows. shapes;

Namespace demo

{

///

/// Interaction logic for window1.xaml

///

Public partial class window1: Window

{

Public window1 ()

{

Initializecomponent ();

}

}

}

Window1 inherits the system. Windows. window class. The main function of the initializecomponent () method is to read the attribute values of the specified window element in the window1.xaml file. The Code is as follows:

[System. Diagnostics. debuggernonusercodeattribute ()]

Public void initializecomponent (){

If (_ contentloaded ){

Return;

}

_ Contentloaded = true;

System. Uri resourcelocater = new system. Uri ("/demo; component/window1.xaml", system. urikind. Relative );

# Line 1 "... window1.xaml"

System. Windows. application. loadcomponent (this, resourcelocater );

# Line default

# Line hidden

}

Add two controls and understand the Event Processing Mechanism

Now I want to add a text control, and then add a button. When the button is clicked, the content of the text control will be modified. Drag the textbox and button to the window1 window through Toolbox. The content of the current window1.xaml file is changed:
<Window X: class = "demo. window1"
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "window1" Height = "300" width = "300">
<Grid>
<Textbox Height = "23" margin = "80, 46, 78,0" name = "textbox1" verticalignment = "TOP"/>
<Button Height = "23" margin = "101,0, 103,59" name = "button1" verticalignment = "bottom"> press </button>
</GRID>
</WINDOW>

The grid control is used to precisely locate the control position. Grid now contains two child controls. The text press displayed by the button control is in the middle of the <button...> and </button> packages.

Observe the three arrows of the press button. The arrows direct to the bottom represent verticalignment = "bottom". The vertical alignment is the bottom alignment. Both the left and right arrows exist, so there is no horizontal alignment. The name attribute corresponds to the name of the button object in the C # code. The four values of the margin attribute are left, top, right, and margin. Note that this is related to alignment, and is different from the origin in the upper-left corner of the window we normally use. Since the bottom side is aligned vertically, the top is always 0.

Now add a click event for the press button and add an event to the XAML file <button Height = "23" margin = ", 0, 98,73 "name =" button1 "verticalignment =" bottom "Click =" button#click"

> Press </button>. The traditional Event Selection Method is no longer used here, but the selection is directly prompted in The XAML file. Vs2008 will also create a member function button#click. The Code is as follows:

Public partial class window1: Window

{

Public window1 ()

{

Initializecomponent ();

}

Private void button#click (Object sender, routedeventargs E)

{

}

}

Those familiar with. Net winform development should be able to guess that the delegate mechanism is still used for Event Callback. Sender indicates the event source. Here, it is actually the window1 object itself. Routedevnetargs e allows us to obtain event-related information. Let's add a sentence

System. Windows. MessageBox. Show ("You click me"). A message box is displayed after you click the button.

Here, a sparrow is small, but the example program is over. The method of writing interfaces in XML is indeed more intuitive than the previous code, and lowers the threshold, so that designers with artistic skills can participate. However, because the interface is directly related to software functions, it is impossible to completely separate the interface design and code writing.

Later, I will summarize some knowledge about writing beautiful interfaces.

Bitmapeffect special effect

This article is very detailed, please refer:

Http://www.cnblogs.com/kuku/archive/2007/02/11/647533.html

Rounded corner window without a title bar

Generally, the title bar must be removed from windows in special shapes. Therefore, the windowstyle attribute of the window object must be set to "NONE", the background must be set to transparent, and transparency is allowed. The Code is as follows:

<Window X: class = "demo. window1"

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

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

Title = "window1" Height = "300" width = "300" windowstyle = "NONE" background = "Transparent" allowstransparency = "true">

We can add a border element to set the angle of Four Corners. The Code is as follows:

<Grid name = "border">

<Border cornerradius = "5, 5, 5"> </Border>

<Textbox Height = "23" margin = "85,61, 73,0" name = "textbox1" verticalignment = "TOP"/>

<Button Height = "23" margin = "104,0, 98,73" name = "button1" verticalignment = "bottom" Click = "button#click"> press </button>

</GRID>

Without the title bar, we also need to allow the drag and drop of the window, so we need to handle the left mouse click event. The Code is as follows:

<Window X: class = "demo. window1"

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

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

Title = "window1" Height = "300" width = "300" windowstyle = "NONE" background = "Transparent" allowstransparency = "true" mouseleftbuttondown = "window_mouseleftbuttondown">

<Grid name = "border">

<Border cornerradius = "5, 5, 5" background = "aliceblue"

> </Border>

<Textbox Height = "23" margin = "85,61, 73,0" name = "textbox1" verticalignment = "TOP"/>

<Button Height = "23" margin = "104,0, 98,73" name = "button1" verticalignment = "bottom" Click = "button#click"> press </button>

</GRID>

</WINDOW>

Note: the background color of border cannot be transparent; otherwise, it cannot be dragged. The implementation of the window_mouseleftbuttondown function is very simple. See:

Namespace demo

{

/// <Summary>

/// Interaction logic for window1.xaml

/// </Summary>

Public partial class window1: Window

{

Public window1 ()

{

Initializecomponent ();

}

Private void button#click (Object sender, routedeventargs E)

{

System. Windows. MessageBox. Show ("You click me ");

}

Private void window_mouseleftbuttondown (Object sender, mousebuttoneventargs E)

{

Dragmove ();

}

}

}


So the overall effect should look like this: linear incremental paint brush this paint brush can draw a gradient effect, it is really convenient. For example, the following code:

<Window X: class = "demo. window1"

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

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

Title = "window1" Height = "300" width = "300" windowstyle = "NONE" background = "Transparent" allowstransparency = "true" mouseleftbuttondown = "window_mouseleftbuttondown" name = "Resources">

<Window. Resources>

</Window. Resources>

<Grid name = "border">

<Border cornerradius = "5, 5, 5" background = "aliceblue"> </Border>

<Textbox Height = "23" margin = "85,61, 73,0" name = "textbox1" verticalignment = "TOP"/>

<Button content = "Press" Height = "23" margin = "104,0, 98,73" name = "button1" verticalignment = "bottom" Click = "button#click">

<Button. Background>

<Lineargradientbrush startpoint = "0, 0" endpoint = "1, 1">

<Gradientstop offset = "0" color = "yellow"> </gradientstop>

<Gradientstop offset = "0.5" color = "green"> </gradientstop>

<Gradientstop offset = "1" color = "red"> </gradientstop>

</Lineargradientbrush>

</Button. Background>

</Button>

</GRID>

</WINDOW>

This method of XML nesting does not seem to be available through visual editing tools of vs2008. You still need to manually edit the XAML file. All controls derived from the contentcontrol class in content mode can accommodate other child controls. For example, the following example is from <programming WPF>.

<Window...>

<Button width = "100" Height = "100">

<Textbox width = "75"> edit me

</Textbox>

</Button>

</WINDOW>

The interface is as follows:

You can also use this method, which is more suitable for embedding objects.

<Button width = "100" Height = "100">

<Button. content>

<Image Source = "tom.png"/>

</Button. content>

</Button> some grid layout controls provide convenient layout functions, such as grid, which uses tables to place its child controls. The following example also comes from <programming WPF> ::

<Window ...>





<Grid>





<Grid.RowDefinitions>





<RowDefinition />





<RowDefinition />





<RowDefinition />





</Grid.RowDefinitions>





<Grid.ColumnDefinitions>





<ColumnDefinition />





<ColumnDefinition />





<ColumnDefinition />





</Grid.ColumnDefinitions>





<Button Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2




">A</Button>





<Button Grid.Row="0" Grid.Column="2




">C</Button>





<Button Grid.Row="1" Grid.Column="0" Grid.RowSpan="2




">D</Button>





<Button Grid.Row="1" Grid.Column="1




">E</Button>





<Button Grid.Row="1" Grid.Column="2




">F</Button>





<Button Grid.Row="2" Grid.Column="1




">H</Button>





<Button Grid.Row="2" Grid.Column="2




">I</Button>





</Grid>





</Window>

Use the grid. rowdefinitions sub-element to define three rows, and use grid. columndefinitions to define three columns. Grid. columnspan = "2

"The specified a button occupies two columns of space.

The code below the listview control defines three headers named name, email, and address.

<Listview name = "list">

<Listview. View>

<Gridview columnheadertooltip = "freebird">

<Gridviewcolumn header = "name" width = "100" displaymemberbinding = "{binding Path = firstname}"/>

<Gridviewcolumn header = "email" width = "100" displaymemberbinding = "{binding Path = Email}"/>

<Gridviewcolumn header = "Address" width = "100" displaymemberbinding = "{binding Path = address}"/>

</Gridview>

</Listview. View>

</Listview>

Displaymemberbinding = "{binding Path = firstname}" indicates that the content to be displayed in this column is bound to the firstname attribute of the object referred to by itemsource.

The result is as follows: data is usually obtained from a data source (such as a database) and inserted into the listview control through code. The following shows how to insert data through code:

Listview has an attribute ienumerable itemssource. Itemssource indicates the set of items in the listview. We should assign a data set object to itemssource, whose type is inherited from observablecollection <>, and the observablecollection is ultimately inherited from the ienumerable interface. If each item in listview (representing a row of records) corresponds to a person class. The person code is as follows: (Note that the property name here is the same as the binding name in the previous XAML file)

Public class person

{

Public Person (string name, string email, string address)

{

This. Name = Name;

This. Email = Email;

This. Address = address;

}

Private string name;

Private string email;

Private string address;

Public string name

{

Get

{

Return name;

}

Set

{

Name = value;

}

}

Public String email

{

Get

{

Return email;

}

Set

{

Email = value;

}

}

Public String address

{

Get

{

Return address;

}

Set

{

Address = value;

}

}

}

The set of items can contain multiple items. I designed a set of persons classes that represent items. The Code is as follows:

Public class persons: observablecollection

{

Public persons ()

{

Add (new person ("chenshu", "csfreebird@gmail.com", "101 "));

Add (new person ("Lijing", "sheismylife@sina.com", "102 "));

}

}

The persons constructor creates two person objects as two items. Then the code for entering data in the listview is simple:

Public partial class window1: Window

{

Public window1 ()

{

Initializecomponent ();

List. itemssource = new persons ();

}

..........

}

There is also a simpler approach. Add the person object one by one using the Add method of the listview. Items attribute. For example, the following code:

List. Items. Add (new person ("chenshu", "csfreebird@gmail.com", "D "));

 

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.