WPF系列六

这一章全部讲解绑定.估计还有一章基础知识就讲解完了,后面的可能我就不更新了,都是用工具生成一些数据绑定,2d,3d的效果.我贴上1000多行代码,给大家看看效果没什么意思.

<?xml version="1.0" encoding="utf-8" ?>

<Persons xmlns="">

  <person Name="Person1">

    <ID>1</ID>

    <Name>张三丰</Name>

    <Age>49</Age>

  </person>

  <person Name="Person2">

    <ID>2</ID>

    <Name>阿贵</Name>

    <Age>29</Age>

  </person>

  <person Name="Person3">

    <ID>3</ID>

    <Name>陈世美</Name>

    <Age>103</Age>

  </person>

  <person Name="Person4">

    <ID>4</ID>

    <Name>李小龙</Name>

    <Age>59</Age>

  </person>

</Persons>

一个xml文件.用于数据绑定

<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="编号" DisplayMemberBinding="{Binding XPath=ID}"  Width="100" />

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

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

                    </GridViewColumn>

                </GridView>

            </ListView.View>

        </ListView>

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

        <Button Height="22" Margin="20,0,124,45" Name="button1" VerticalAlignment="Bottom" Click="button1_Click">将XML 文件绑定到元素</Button>

        <Button Height="27" Margin="20,0,124,12" Name="button2" VerticalAlignment="Bottom" Click="button2_Click">将 自定义对象绑定到元素</Button>

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

 

    </Grid>

</Window>

下面是后台绑定代码

namespace WPFBindXML

{

    public partial class Window1 : Window

    {

        public Window1()

        {

            InitializeComponent();

        }

        private void button1_Click(object sender, RoutedEventArgs e)

        {

//让一个listview绑定一个xml文件.

            XmlDocument doc = new XmlDocument();

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

//直接访问xml数据

            XmlDataProvider provider = new XmlDataProvider();

            provider.Document = doc; //绑定到一个xml对象

            provider.XPath = @"/Persons/person"; //xpath查询

            listView1.DataContext = provider;//listview的数据源指向

            listView1.SetBinding(ListView.ItemsSourceProperty, new Binding());//绑定

        }

        private void listView1_SelectionChanged(object sender, SelectionChangedEventArgs e)

        {

            if (e.AddedItems.Count != 0)

            {

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

                this.label1.Content = a.InnerXml;//这个是你选择某一项 把值拿出来

            }

        }

        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一个自定义的数据源

 

当然 我们还可以去绑定一个下拉框的选项值

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; }

    }

}

我们已经了解了绑定xml文件,绑定自定义的对象,以及对象集合.

下面我们来看一个比较复杂的例子,banding自定义模板

<Window x:Class="WPF_自定义对象绑定.Window1"

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

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

  xmlns:local="clr-namespace:WPF_自定义对象绑定"

  SizeToContent="WidthAndHeight"

  Title="WPF_自定义对象绑定" Background="#FF00CCCC">

//这个资源里面 我们又学习了新东西 就是自定义模板  这个也可以放在资源里面的

    <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_自定义对象绑定" Height="73" Name="label1" FontSize="24" Width="426" />

        <TextBlock Margin="10,0,0,0">选择项</TextBlock>      

        <ListBox SelectionChanged="ListBox_SelectionChanged"

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

            <ListBoxItem>第一条</ListBoxItem>

            <ListBoxItem>第二条</ListBoxItem>

            <ListBoxItem>第三条</ListBoxItem>

        </ListBox>    

//让listbox去指定一个自定义的模板

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

                 HorizontalContentAlignment="Stretch"

                 ItemsSource="{Binding}"

                 ItemTemplate="{StaticResource UserDataTemp}"/>

    </StackPanel>

</Window>

//后台绑定的代码

namespace WPF_自定义对象绑定

{

    public partial class Window1 : Window

    {

        Users users = new Users();//初始化数据

        public Window1()

        {

            InitializeComponent();

            users.Add(new User(1, "asdf", "北京市东城区", "chk", "1111"));

            users.Add(new User(2, "王三", "北京市朝阳区", "sss", "234"));

            users.Add(new User(3, "刘金金", "北京市朝阳区", "ppp", "888"));

            users.Add(new User(4, "程晓春", "北京市海淀区", "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;

        }

    }

}

下面是自定义的对象代码

using System.ComponentModel;

using System.Collections.ObjectModel;

 

namespace WPF_自定义对象绑定

{

//向客户端发出某一属性值已更改的通知, 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");//有更改就触发这个事件

            }

        }

        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));

            }

        }

}

//这个类 和List<User>相等..

    public class Users : ObservableCollection<User>

    {

        public Users()

            : base()

        { }

    }

}

忘了告诉大家怎么绑定dataTable了,不过我相信大家也是会的,不会的可以看看下面的代码.

CREATE TABLE [dbo].[Table_1](  [Id] [nvarchar](50) NULL,  [Name] [nvarchar](50) NULL ) 创建一个最简单的表,就两个字段

<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,12,12,121" Name="listView1">            

<ListView.View>                

<GridView>                    

<GridViewColumn Header="编号" DisplayMemberBinding="{Binding Path=Id}" Width="100" />                    

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

 </GridView>            

</ListView.View>        

</ListView>    

</Grid>

</Window>

代码比较乱,大家复制过去看看就行了.

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());   

      }  

   }

 }

代码比较简单,不说了,我就是随便写了几行代码,测试用的.

原文地址:https://www.cnblogs.com/chenmengmeng/p/2331764.html