本文来源 http://wshoufeng1989.blog.163.com/blog/static/202047033201282911633670/
风随影动的博客
使用数据库AllData ,我们的程序会从S_Province表中读取数据,并绑定! 表结构如图所示:
程序将读取城市名称,创建时间,修改时间,列在一个WPF ListBox控件。最后的ListBox如图所示:
现在来看我们的XAML文件。创建数据模板listBoxTemplate。数据模板有三块,第一块显示的是城市名称;第二块显示的是创建日期;第三块显示的是更新日期
1 <Window x:Class="ListBox_SqlData_WPF.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="MainWindow" Height="350" Width="525"> 5 <Window.Resources> 6 <DataTemplate x:Key="listBoxTemplate"> 7 <StackPanel Margin="4"> 8 <DockPanel> 9 <TextBlock FontWeight="Bold" Text="城市名称:" DockPanel.Dock="Left" Margin="5,0,10,0"/> 10 <TextBlock Text=" "/> 11 <TextBlock Text="{Binding ProvinceName}" Foreground="Green" FontWeight="Bold"/> 12 </DockPanel> 13 <DockPanel> 14 <TextBlock FontWeight="Bold" Text="创建日期:" DockPanel.Dock="Left" Margin="5,0,5,0"/> 15 <TextBlock Text=" "/> 16 <TextBlock Text="{Binding DateCreated}" Foreground="DarkOrange"/> 17 </DockPanel> 18 <DockPanel> 19 <TextBlock FontWeight="Bold" Text="更新日期:" DockPanel.Dock="Left" Margin="5,0,5,0"/> 20 <TextBlock Text=" "/> 21 <TextBlock Text="{Binding DateUpdated}" Foreground="Cyan"/> 22 </DockPanel> 23 </StackPanel> 24 </DataTemplate> 25 </Window.Resources> 26 <Grid>
1 <ListBox Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}" 2 ItemTemplate="{StaticResource listBoxTemplate}"/> 3 </Grid> 4 </Window>
后台代码
1 public partial class MainWindow : Window 2 { 3 string sql = "select ProvinceName,DateCreated,DateUpdated from S_Province"; 4 string connectionString = "server=localhost;uid=sa;pwd=123456;database=AllData;"; 5 6 public MainWindow() 7 { 8 InitializeComponent(); 9 BindData(); 10 } 11 12 private void BindData() 13 { 14 DataSet ds = new DataSet(); 15 using (SqlConnection sqlcn = new SqlConnection(connectionString)) 16 { 17 using (SqlCommand cmd = new SqlCommand(sql, sqlcn)) 18 { 19 SqlDataAdapter adapter = new SqlDataAdapter(); 20 sqlcn.Open(); 21 adapter.SelectCommand = cmd; 22 adapter.Fill(ds, "province"); 23 listBox1.DataContext = ds; 24 } 25 } 26 } 27 }