WPF编程宝典第19章的数据绑定详解(一)

本文修改自《WPF编程宝典2012》第19章第19.1.1~19.1.3节的内容,因为原书中很多实现的细节未列出,所以自己重新编写了一下代码,更细的的进行补充原书中的遗漏漏。数据库文件,使用使用书中自带的store.sql在SqlServer2008中创建store数据库。

 

在VS2012中新建一个WPF项目wpf19.1。

 

第一步:在解决方案中添加一个类库"StoreDatabase"项目,在此项目中分别添加三个类文件,分别是StoreDB.cs、StoreDbDataSet.cs、Product.cs。

Product.cs代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace StoreDatabase
{
    public class Product
    {
        private string modelNumber;
        public string ModelNumber
        {
            get
            {
                return modelNumber;
            }
            set
            {
                modelNumber = value;
            }
        }

        public string modelName;
        public string ModelName
        {
            get { return modelName; }
            set { modelName = value; }
        }

        public decimal unitCost;
        public decimal UnitCost
        {
            get { return unitCost; }
            set { unitCost = value;}
        }

        public string description;
        public string Description
        {
            get { return description; }
            set { description = value; }
        }

        public Product(string modelNumber, string modelName, decimal unitCost, string description)
        {
            ModelNumber = modelNumber;
            ModelName = modelName;
            UnitCost = unitCost;
            Description = description;
        }
    
    }//end class
}

  

 

StoreDbDataSet.cs使用来访问本机SqlServer数据库,并返回查询结果集的代码。注释掉的地方是访问XML数据文件的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace StoreDatabase
{
    class StoreDbDataSet
    {
        public DataTable GetProducts()
        {
            return ReadDataSet().Tables[0];
        }

        public DataSet GetCategoriesAndProducts()
        {
            return ReadDataSet();
        }

        internal static DataSet ReadDataSet()
        {
            //访问xml的数据文件
            //DataSet ds = new DataSet();
            //ds.ReadXmlSchema("store.xsd");
            //ds.ReadXml("store.xml");
            //return ds;

            //访问本机sqlserver数据库
            DataSet ds = new DataSet();

            string conString = "Password=*******;Persist Security Info=True;User ID=sa;Initial Catalog=store;Data Source=******";

            SqlConnection sqlCon = new SqlConnection(conString);

            //GetProducts 是数据库中预先设定的“存储过程”
            SqlDataAdapter myDataAdapter = new SqlDataAdapter("GetProducts", sqlCon);

            myDataAdapter.Fill(ds, "Products");

            return ds;

        }
    }//end class
}//end namespace

  

 

StoreDbDataSet.cs中的代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;
using System.Collections.ObjectModel;

namespace StoreDatabase
{
    public class StoreDB
    {
        public Product GetProduct(int ID)
        {
            DataSet ds = StoreDbDataSet.ReadDataSet();
            DataRow productRow = ds.Tables["Products"].Select("ProductId=" + ID.ToString())[0];
            Product product = new Product((string)productRow["ModelNumber"], (string)productRow["ModelName"],
                (decimal)productRow["UnitCost"], (string)productRow["Description"]);

            return product;
        }
    }//end class
}

  

右键在"解决方案资源管理器"中的类库项目上点击”生成“,则会生成StoreDatabase.dll文件。

 

第二步:在主启动项目中添加引用 StoreDatabase.dll 文件。

 

在APP.cs文件中添加代码,添加后的代码如下所示,在全局的APP类中添加公有静态对象storeDB,可以在项目中多窗口中共享使用此对象进行数据获得。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using StoreDatabase;

namespace Wpf19._1
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private static StoreDB storeDB = new StoreDB();
        public static StoreDB StoreDB
        {
            get { return storeDB; }
        }
    }
}

 

需要绑定数据的XAML窗台的代码:

<Window x:Class="Wpf19._1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="BindProductObject" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <TextBlock Margin="7">Product ID:</TextBlock>
            <TextBox Margin="5" x:Name="txtID" Grid.Column="1">356</TextBox>
            <Button x:Name="cmdGetProduct" Grid.Column="2" Margin="5" Padding="2" Click="cmdGetProduct_Click">Get Product</Button>
        </Grid>
        <Border Grid.Row="1" Padding="7" Margin="7" Background="LightSteelBlue">
            <Grid x:Name="gridProductDetails">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="Auto"></RowDefinition>
                    <RowDefinition Height="*"></RowDefinition>
                </Grid.RowDefinitions>
                <TextBlock Margin="7" >Model Number:</TextBlock>
                <TextBox Margin="5" Grid.Column="1" Text="{Binding Path=ModelNumber}"></TextBox>

                <TextBlock Margin="7" Grid.Row="1" >Model Name:</TextBlock>
                <TextBox Margin="5" Grid.Column="1" Grid.Row="1" Text="{Binding Path=ModelName}"></TextBox>

                <TextBlock Margin="7" Grid.Row="2" >Unit Cost:</TextBlock>
                <TextBox Margin="5" Grid.Column="1" Grid.Row="2" Text="{Binding Path=UnitCost}"></TextBox>
                
                <TextBlock Margin="7,7,7,0" Grid.Row="3">Description</TextBlock>
                <TextBox Margin="7" Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"
                         TextWrapping="Wrap" Text="{Binding Path=Description}"></TextBox>

            </Grid>
        </Border>
    </Grid>
</Window>

  

按钮 Product ID 的click事件处理代码

  private void cmdGetProduct_Click(object sender, RoutedEventArgs e)
        {
            int ID;
            if (Int32.TryParse(txtID.Text, out ID))
            {
                try
                {
                    gridProductDetails.DataContext = App.StoreDB.GetProduct(ID);
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else
            {
                MessageBox.Show("Invalid ID.");
            }
           

        }

  

 

posted on 2015-08-25 17:42  袁州东东  阅读(261)  评论(0编辑  收藏  举报