mysql绑定gridview_WPF将数据库和GridView绑定并更改GridView模板

首先来看一下如何使用GridView,在前台的话代码如下:这里仅仅举出一个例子,GridView是作为子项嵌套在ListView中的,这里的数据源是通过绑定的方式来绑定到GridView中的。

DisplayMemberBinding="{Binding Path=ProductID}">

DisplayMemberBinding="{Binding Path=ProductName}">

DisplayMemberBinding="{Binding Path=SupplierID}">

DisplayMemberBinding="{Binding Path=CategoryID}">

DisplayMemberBinding="{Binding Path=QuantityPerUnit}">

DisplayMemberBinding="{Binding Path=UnitPrice}">

DisplayMemberBinding="{Binding Path=UnitInStock}">

这里有一些关键字,Header和DisplayMemberBinding,在前台中我们可以通过修改模板的方式来修改GridView的样式,首先我们可以修改GridView的列头的样式,我们可以改变背景,字体大小,高度等一系列参数。

另外还有一个重要的模板,就是CellTemplate,我们需要注意GridViewColumn用了DisplayMemberBinding 使得CellTemplate失效,所以如果需要自定义CellTemplate,那么一定要去掉DisplayMemberBinding。 下面是一个具体的例子。

首先在资源中定义模板,

然后在具体的列中引用,这样就可以实现对每一列的模板替换。

还有很重要的一部分就是在后台来讲数据库绑定到前台中,在xaml中我们使用了ItemsSource="{Binding}",那么在后台的代码中:

///

/// 从数据库中获取数据并绑定到GridView上

///

private void GetDataFromDataBase()

{

string connectStr = "Server=127.0.0.1;Database=test;Uid=root;Pwd=12345;Port=3306;CharSet=gbk;allow zero datetime=true";

string cmdStr = "select * from camerainfo order by pID desc limit 100";

DataBaseMySqlHander sql = new DataBaseMySqlHander(connectStr);

DataTable dt = sql.GetDataTable(cmdStr);

if (dt == null) return;

//创建一个DataTable的副本

DataTable tempTable = new DataTable();

tempTable = dt.Clone();//克隆 System.Data.DataTable 的结构

//包括所有 System.Data.DataTable 架构和约束。

if (tempTable != null && dt.Rows.Count>0)

{

for (int i = 0; i < dt.Rows.Count; i++)

{

tempTable.ImportRow(dt.Rows[i]);

}

}

//为ListView绑定数据源

this.dv= tempTable.DefaultView;

tempTable.Dispose();

}

以上部分就实现了简单的数据库的绑定,这部分也是非常重要的部分,我们在使用的时候可以按照上述步骤来进行绑定!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值