WPF ListBox数据绑定

本文来源 http://wshoufeng1989.blog.163.com/blog/static/202047033201282911633670/

 风随影动的博客

使用数据库AllData ,我们的程序会从S_Province表中读取数据,并绑定! 表结构如图所示:

WPF ListBox数据绑定
程序将读取城市名称,创建时间,修改时间,列在一个WPF ListBox控件。最后的ListBox如图所示:
WPF ListBox数据绑定

现在来看我们的XAML文件。创建数据模板listBoxTemplate。数据模板有三块,第一块显示的是城市名称;第二块显示的是创建日期;第三块显示的是更新日期

 <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="" Width="">
<Window.Resources>
<DataTemplate x:Key="listBoxTemplate">
<StackPanel Margin="">
<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 Margin="17,8,15,26" Name="listBox1" ItemsSource="{Binding Tables[0]}"
ItemTemplate="{StaticResource listBoxTemplate}"/>
</Grid>
</Window>
后台代码
 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;
}
}
}
}
上一篇:Compiling JSPs Using the Command-Line Compiler---官方


下一篇:你必须收藏的Github技巧