首页 > 代码库 > WPF DataGrid、ListView 简单绑定

WPF DataGrid、ListView 简单绑定

DataGrid运行效果: xaml 代码: DataGridName= dtgData ItemsSource= {Binding} AutoGenerateColumns= False DataGrid.Columns DataGridTextColumnBinding= {BindingPath=id} Header= ID HeaderStringFormat= id / DataGridTextColumnBinding= {BindingPath=name} Header= 名称 Header

  

  DataGrid运行效果:

  

 

  xaml 代码:

       <DataGrid Name="dtgData"  ItemsSource="{Binding}"  AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Path=id}" Header="ID" HeaderStringFormat="id"/>
                <DataGridTextColumn Binding="{Binding Path=name }" Header="名称" HeaderStringFormat="name" />
                <DataGridTextColumn Binding="{Binding Path=level }" Header="等级" HeaderStringFormat="level" />
            </DataGrid.Columns>
        </DataGrid>

  cs 代码:

       private void BindData()
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "server=192.168.....;database=hospital;uid=sa;pwd=123456";
            SqlCommand comm = new SqlCommand();
            string  strSql="select * from address";
            comm.CommandType = CommandType.Text;
            DataTable dt = new DataTable();
            conn.Open();
            SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);
            sda.Fill(dt);
            dtgData.ItemsSource = dt.DefaultView;
        }

  ListView 运行效果:

  

 

  xaml 代码:

        <ListView  Name="ltvData">
            <ListView.View >
                <GridView x:Name="gvw1">
                    <GridViewColumn  Header="ID"  DisplayMemberBinding="{Binding Path=id}"></GridViewColumn>
                    <GridViewColumn  Header="名称" DisplayMemberBinding="{Binding Path=name}"></GridViewColumn>
                    <GridViewColumn  Header="等级" DisplayMemberBinding="{Binding Path=level}"></GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

  cs 代码:

  //数据绑定
        private void BindData(string strSql)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = "server=.;database=hospital;uid=sa;pwd=123456";
            SqlCommand comm = new SqlCommand();
            comm.CommandType = CommandType.Text;
            DataTable dt = new DataTable();
            conn.Open();
            SqlDataAdapter sda = new SqlDataAdapter(strSql, conn);
            sda.Fill(dt);
            ltvData.ItemsSource = dt.DefaultView;
        }         

  本文来自zhangqynuli的博客,原文地址:http://hi.baidu.com/zhangqynuli/blog/item/f96d41c9236a6359f31fe707.html