WPF ListBox数据绑定


使用数据库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="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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值