使用数据库AllData ,我们的程序会从S_Province表中读取数据,并绑定! 表结构如图所示:
程序将读取城市名称,创建时间,修改时间,列在一个WPF ListBox控件。最后的ListBox如图所示:
<Window x:Class="ListBox_SqlData_WPF.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <DataTemplate x:Key="listBoxTemplate"> <StackPanel Margin="4"> <DockPanel> <TextBlock FontWeight="Bold" Text="城市名称:" DockPanel.Dock="Left" Margin="5,0,10,0"/> <TextBlock Text=" "/> <TextBlock Text="{Binding ProvinceName}" Foreground="Green" FontWeight="Bold"/> </DockPanel> <DockPanel> <TextBlock FontWeight="Bold" Text="创建日期:" DockPanel.Dock="Left" Margin="5,0,5,0"/> <TextBlock Text=" "/> <TextBlock Text="{Binding DateCreated}" Foreground="DarkOrange"/> </DockPanel> <DockPanel> <TextBlock FontWeight="Bold" Text="更新日期:" DockPanel.Dock="Left" Margin="5,0,5,0"/> <TextBlock Text=" "/> <TextBlock Text="{Binding DateUpdated}" Foreground="Cyan"/> </DockPanel> </StackPanel> </DataTemplate> </Window.Resources> <Grid>添加一个ListBox控件,设置资源及模板 <ListBox Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}" ItemTemplate="{StaticResource listBoxTemplate}"/> </Grid> </Window>
CS
public partial class MainWindow : Window { string sql = "select ProvinceName,DateCreated,DateUpdated from S_Province"; string connectionString = "server=localhost;uid=sa;pwd=123456;database=AllData;"; public MainWindow() { InitializeComponent(); BindData(); } private void BindData() { DataSet ds = new DataSet(); using (SqlConnection sqlcn = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(sql, sqlcn)) { SqlDataAdapter adapter = new SqlDataAdapter(); sqlcn.Open(); adapter.SelectCommand = cmd; adapter.Fill(ds, "province"); listBox1.DataContext = ds; } } } }转自:http://wshoufeng1989.blog.163.com/blog/static/202047033201282911633670/