WPF Series 6

Source: Internet
Author: User

This chapter describes binding. it is estimated that there is still a chapter of basic knowledge that will be explained, and I may not update it later. We will use tools to generate some data binding, 2d and 3d effects. I pasted more than 1000 lines of code to show you the effect.

<? Xml version = "1.0" encoding = "UTF-8"?>

<Persons xmlns = "">

<Person Name = "Person1">

<ID> 1 </ID>

<Name> Zhang Sanfeng </Name>

<Age> 49 </Age>

</Person>

<Person Name = "Person2">

<ID> 2 </ID>

<Name> Agui </Name>

<Age> 29 </Age>

</Person>

<Person Name = "Person3">

<ID> 3 </ID>

<Name> Chen Shimei </Name>

<Age> 103 </Age>

</Person>

<Person Name = "Person4">

<ID> 4 </ID>

<Name> Bruce Lee </Name>

<Age> 59 </Age>

</Person>

</Persons>

An xml file for Data Binding

<Window x: Class = "WPFBindXML. Window1"

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

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

Title = "Window1" Height = "334" Width = "496">

<Grid>

 

<ListView Margin = "12, 12, 12,121" Name = "listView1" SelectionChanged = "listView1_SelectionChanged">

<ListView. View>

<GridView>

<GridViewColumn Header = "no." DisplayMemberBinding = "{Binding XPath = ID}" Width = "100"/>

<GridViewColumn Header = "Name" DisplayMemberBinding = "{Binding XPath = Name}" Width = "100"/>

<GridViewColumn Header = "Age" DisplayMemberBinding = "{Binding XPath = Age}" Width = "100">

</GridViewColumn>

</GridView>

</ListView. View>

</ListView>

<Label Height = "25" Margin = "12, 0, 12, 90" Name = "label1" verticalignment = "Bottom"> </Label>

<Button Height = "22" Margin = "20, 0, 124,45" Name = "button1" verticalignment = "Bottom" Click = "button#click"> bind an XML file to an element </Button>

<Button Height = "27" Margin = "20, 0, 124,12 "Name =" button2 "verticalignment =" Bottom "Click =" button2_Click "> bind a custom object to an element </Button>

<ComboBox Name = "com1" Height = "20" Width = "200"/>

 

</Grid>

</Window>

The following is the background binding code.

Namespace WPFBindXML

{

Public partial class Window1: Window

{

Public Window1 ()

{

InitializeComponent ();

}

Private void button#click (object sender, RoutedEventArgs e)

{

// Bind a listview to an xml file.

XmlDocument doc = new XmlDocument ();

Doc. Load (@ ".. \ XMLFile1.xml ");

// Directly access xml data

XmlDataProvider provider = new XmlDataProvider ();

Provider. Document = doc; // bind to an xml Object

Provider. XPath = @ "/Persons/person"; // xpath Query

ListView1.DataContext = provider; // the data source of listview points

ListView1.SetBinding (ListView. ItemsSourceProperty, new Binding (); // bind

}

Private void listviewincluselectionchanged (object sender, SelectionChangedEventArgs e)

{

If (e. AddedItems. Count! = 0)

{

XmlElement a = (XmlElement) e. AddedItems [0];

This. label1.Content = a. InnerXml; // you choose to take out a value.

}

}

Private void button2_Click (object sender, RoutedEventArgs e)

{

// Pesrsion P = new Pesrsion ("1", "CHK76REN", "20 ");

// Binding myBinding = new Binding ("Name ");

// MyBinding. Source = P;

// Label1.SetBinding (Label. ContentProperty, myBinding );

// Banding A Custom Data Source

 

Of course, we can also bind an option value in the drop-down box.

List <Pesrsion> pes = new List <Pesrsion> ();

Pes. Add (new Pesrsion () {ID = "1", Name = "1", Age = "1 "});

Pes. Add (new Pesrsion () {ID = "1", Name = "2", Age = "1 "});

Pes. Add (new Pesrsion () {ID = "1", Name = "3", Age = "1 "});

Pes. Add (new Pesrsion () {ID = "1", Name = "4", Age = "1 "});

Com1.ItemsSource = pes;

Com1.DisplayMemberPath = "Name ";

 

}

}

Public class Pesrsion

{

Public Pesrsion (string id, string name, string age)

{

This. ID = id;

This. Name = name;

This. Age = age;

}

Public string ID {get; set ;}

Public string Age {get; set ;}

Public string Name {get; set ;}

}

}

We have learned about binding xml files, binding custom objects, and object sets.

The following is a complicated example of a banding custom template.

<Window x: Class = "WPF _ custom object binding. Window1"

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

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

Xmlns: local = "clr-namespace: WPF _ custom object binding"

SizeToContent = "WidthAndHeight"

Title = "WPF _ binding a custom object" Background = "# FF00CCCC">

// In this resource, we have learned new things, that is, custom templates. This can also be placed in resources.

<Window. Resources>

<DataTemplate x: Key = "UserDataTemp">

<Border Name = "border" BorderBrush = "Aqua" BorderThickness = "1"

Padding = "5" Margin = "5">

<Grid>

<Grid. RowDefinitions>

<RowDefinition/>

<RowDefinition/>

<RowDefinition/>

<RowDefinition/>

<RowDefinition/>

</Grid. RowDefinitions>

<Grid. ColumnDefinitions>

<ColumnDefinition/>

<ColumnDefinition/>

</Grid. ColumnDefinitions>

<TextBlock Grid. Row = "0" Grid. Column = "0" Text = "ID:"/>

<TextBlock Grid. Row = "0" Grid. Column = "1" Text = "{Binding Path = Id}"/>

<TextBlock Grid. Row = "1" Grid. Column = "0" Text = "Name:"/>

<TextBlock Grid. Row = "1" Grid. Column = "1" Text = "{Binding Path = Name}"/>

<TextBlock Grid. Row = "2" Grid. Column = "0" Text = "Address:"/>

<TextBlock Grid. Row = "2" Grid. Column = "1" Text = "{Binding Path = Address}"/>

<TextBlock Grid. Row = "3" Grid. Column = "0" Text = "UserName:"/>

<TextBlock Grid. Row = "3" Grid. Column = "1" Text = "{Binding Path = UserName}"/>

<TextBlock Grid. Row = "4" Grid. Column = "0" Text = "PassWord:"/>

<TextBlock Grid. Row = "4" Grid. Column = "1" Text = "{Binding Path = PassWord}"/>

</Grid>

</Border>

</DataTemplate>

</Window. Resources>

<StackPanel>

<Label Content = "WPF _ custom object binding" Height = "73" Name = "label1" FontSize = "24" Width = "426"/>

<TextBlock Margin = ", 0,"> select item </TextBlock>

<ListBox SelectionChanged = "ListBox_SelectionChanged"

SelectedIndex = "0" Margin = "10, 0, 10, 0">

<ListBoxItem> Article 1 </ListBoxItem>

<ListBoxItem> Article 2 </ListBoxItem>

<ListBoxItem> Article 3 </ListBoxItem>

</ListBox>

// Let listbox specify a custom template

<ListBox Width = "400" Margin = "10" Name = "myListBox"

HorizontalContentAlignment = "Stretch"

ItemsSource = "{Binding }"

ItemTemplate = "{StaticResource UserDataTemp}"/>

</StackPanel>

</Window>

// Code bound to the background

Namespace WPF _ custom object binding

{

Public partial class Window1: Window

{

Users users = new Users (); // initialize data

Public Window1 ()

{

InitializeComponent ();

Users. Add (new User (1, "asdf", "Dongcheng District, Beijing", "chk", "1111 "));

Users. Add (new User (2, "Wang San", "Chaoyang District, Beijing", "sss", "234 "));

Users. Add (new User (3, "Liu Jinjin", "Chaoyang District, Beijing", "ppp", "888 "));

Users. Add (new User (4, "Cheng xiaochun", "Haidian District, Beijing", "ppp", "888 "));

}

Private void ListBox_SelectionChanged (object sender, SelectionChangedEventArgs e)

{

Int id = (sender as ListBox). SelectedIndex + 1;

This. DataContext = from u in users where u. Id = id select u;

}

}

}

The following is the custom object code.

Using System. ComponentModel;

Using System. Collections. ObjectModel;

 

Namespace WPF _ custom object binding

{

// Send a notification to the client that the property value has been changed. The meaning of InotifyPropertyChanged

Public class User: INotifyPropertyChanged

{

Private int id;

Private string name;

Private string address;

Private string username;

Private string password;

Public event PropertyChangedEventHandler PropertyChanged;

Public User ()

{

}

Public User (int id, string name, string address, string username, string password)

{

This. id = id;

This. name = name;

This. address = address;

This. username = username;

This. password = password;

}

Public override string ToString ()

{

Return name. ToString ();

}

Public int Id

{

Get {return id ;}

Set

{

Id = value;

OnPropertyChanged ("Id"); // This event is triggered when there is a change.

}

}

Public string Name

{

Get {return name ;}

Set

{

Name = value;

OnPropertyChanged ("Name ");

}

}

Public string Address

{

Get {return address ;}

Set

{

Address = value;

OnPropertyChanged ("Address ");

}

}

Public string UserName

{

Get {return username ;}

Set

{

Username = value;

OnPropertyChanged ("UserName ");

}

}

Public string PassWord

{

Get {return password ;}

Set

{

Password = value;

OnPropertyChanged ("PassWord ");

}

}

Protected void OnPropertyChanged (string info)

{

PropertyChangedEventHandler handler = PropertyChanged;

If (handler! = Null)

{

Handler (this, new PropertyChangedEventArgs (info ));

}

}

}

// This class is equal to List <User> ..

Public class Users: ObservableCollection <User>

{

Public Users ()

: Base ()

{}

}

}

I forgot to tell you how to bind the dataTable, But I believe everyone will do the same. If not, you can look at the following code.

Create table [dbo]. [Table_1] ([Id] [nvarchar] (50) NULL, [Name] [nvarchar] (50) NULL) create a simplest table with two fields

<Window x: Class = "WPFBindXML. Window2" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Window2" Height = "334" Width = "496">

<Grid>

<ListView Margin = "12,121," Name = "listView1">

<ListView. View>

<GridView>

<GridViewColumn Header = "no." DisplayMemberBinding = "{Binding Path = Id}" Width = "100"/>

<GridViewColumn Header = "Name" DisplayMemberBinding = "{Binding Path = Name}" Width = "100"/>

</GridView>

</ListView. View>

</ListView>

</Grid>

</Window>

The code is messy. Just copy it and check it out.

Namespace WPFBindXML

{

Public partial class Window2: Window

{

Public Window2 ()

{

InitializeComponent ();

String conStr = "server =.; uid = sa; pwd = 1; database = ZuoYe ";

SqlConnection con = new SqlConnection (conStr );

String SQL = "select * from Table_1 ";

SqlCommand cmd = new SqlCommand (SQL, con );

SqlDataAdapter adapter = new SqlDataAdapter (cmd );

DataSet ds = new DataSet ();

Adapter. Fill (ds );

This. listView1.DataContext = ds. Tables [0]. DefaultView;

ListView1.SetBinding (ListView. ItemsSourceProperty, new Binding ());

}

}

}

The code is relatively simple. I just wrote a few lines of code for testing.

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.