1最近在学习传智播客杨中科老师的win8开发视频,但是苦于本人的计算机配置太苦逼了,不能开发win8程序,只能用WPF开发一个小程序,但是Xaml语言WFP,Silverlight,Win8,WP8都是想通的,几乎一模一样

 程序初始界面

通过添加数据之后展示如下:

程序本身是比较简单,但是其中包含了其它一般项目所没有的新功能

首先声明一个Student类,它的属性都是依赖属性:

   public class Student : DependencyObject
        {

 

            public int p_rowIndex
            {
                get { return (int)GetValue(p_rowIndexProperty); }
                set { SetValue(p_rowIndexProperty, value); }
            }

            // Using a DependencyProperty as the backing store for p_rowIndex.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty p_rowIndexProperty =
                DependencyProperty.Register("p_rowIndex", typeof(int), typeof(Student),
                null);


            public int p_id
            {
                get { return (int)GetValue(p_idProperty); }
                set { SetValue(p_idProperty, value); }
            }

            // Using a DependencyProperty as the backing store for p_id.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty p_idProperty =
                DependencyProperty.Register("p_id", typeof(int), typeof(Student),
                null);

 

            public string p_name
            {
                get { return (string)GetValue(p_nameProperty); }
                set { SetValue(p_nameProperty, value); }
            }

            // Using a DependencyProperty as the backing store for p_name.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty p_nameProperty =
                DependencyProperty.Register("p_name", typeof(string), typeof(Student),
               null);

 

            public string p_sex
            {
                get { return (string)GetValue(p_sexProperty); }
                set { SetValue(p_sexProperty, value); }
            }

            // Using a DependencyProperty as the backing store for p_sex.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty p_sexProperty =
                DependencyProperty.Register("p_sex", typeof(string), typeof(Student), null);

 

            public string p_sfz
            {
                get { return (string)GetValue(p_sfzProperty); }
                set { SetValue(p_sfzProperty, value); }
            }

            // Using a DependencyProperty as the backing store for p_sfz.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty p_sfzProperty =
                DependencyProperty.Register("p_sfz", typeof(string), typeof(Student), null);

 

            public string p_address
            {
                get { return (string)GetValue(p_addressProperty); }
                set { SetValue(p_addressProperty, value); }
            }

            // Using a DependencyProperty as the backing store for p_address.  This enables animation, styling, binding, etc...
            public static readonly DependencyProperty p_addressProperty =
                DependencyProperty.Register("p_address", typeof(string), typeof(Student), null);

 

        }

//后台逻辑代码: 

//Access数据库连接字符串
        private string connStr = ConfigurationManager.ConnectionStrings["OledbConnStr"].ConnectionString;
        //ObservableCollection 集合类,他的特性是:有新数据加入时,他会自动通知UI,展示新数据的,他自己实现了INotifyPropertyChanged,实现了事件通知机制
        private ObservableCollection<Student> oblist = new ObservableCollection<Student>();

        /// <summary>
        /// 添加新数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            string a, b, c, d, f;
            int index;
            a = tb_XM.Text;
            b = (rb_Nan.IsChecked == true) ? rb_Nan.Tag.ToString() : rb_Nu.Tag.ToString();
            c = tb_SFZH.Text;
            d = tb_JTDZ.Text;
            f = DateTime.Now.ToString("MMddHHmmms");
            if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(c))
            {
                MessageBox.Show("请输入姓名和身份证号!!");
                return;

            }
            ///通过oledb向access数据库添加数据
            using (OleDbConnection connection = new OleDbConnection(connStr))
            {
                using (OleDbCommand command = new OleDbCommand())
                {
                    connection.Open();
                    string sql = "insert into Student(p_id,p_name,p_sex,p_sfz,p_address) values('" + f + "','" + a + "','" + b + "','" + c + "','" + d + "')";
                    command.Connection = connection;
                    command.CommandText = sql;
                    index = command.ExecuteNonQuery();

                }
            }

            if (index > 0)
            {
                MessageBox.Show("添加成功!!");
            }
            else
            {
                MessageBox.Show("添加失败!");
            }

        }

 

        /// <summary>
        /// 查看列表信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearchList_Click(object sender, RoutedEventArgs e)
        {
            //从access数据库读取数据
            using (OleDbConnection connection = new OleDbConnection(connStr))
            {
                using (OleDbCommand command = new OleDbCommand())
                {
                    connection.Open();
                    string sql = "select * from Student";
                    command.Connection = connection;
                    command.CommandText = sql;
                    OleDbDataReader rd = command.ExecuteReader();
                    int index = 0;

                    while (rd.Read())
                    {
                        index++;
                        Student stu = new Student();
                        stu.p_rowIndex = index;
                        stu.p_id = Convert.ToInt32(rd["p_id"]);
                        stu.p_name = rd["p_name"].ToString();
                        stu.p_sex = rd["p_sex"].ToString();
                        stu.p_sfz = rd["p_sfz"].ToString();
                        stu.p_address = rd["p_address"].ToString();
                        oblist.Add(stu);
                    }

                }
            }
            DetilList dl = new DetilList(oblist);
            dl.Show();
        }

前台数据录入代码:<Window x:Class="WPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="通过传智播客Win8学习后-学生信息管理系统" ResizeMode="NoResize" FontSize="22" Height="300" Width="600">
    <Grid x:Name="Layout">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto" MinWidth="471"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="姓名:" />
        <TextBlock Text="性别:" Grid.Row="1"/>
        <TextBlock Text="身份证号:" Grid.Row="2"/>
        <TextBlock Text="家庭地址:" Grid.Row="3"/>
        <TextBox x:Name="tb_XM" Width="220" HorizontalAlignment="Left" Grid.Column="1" Margin="9,0"/>
        <StackPanel Grid.Row="1"  Margin="9,0" HorizontalAlignment="Left" Orientation="Horizontal" Grid.Column="1">
            <RadioButton Content="男" Name="rb_Nan" Tag="1" IsChecked="True"  GroupName="a"></RadioButton>
            <RadioButton Content="女" Name="rb_Nu" Tag="2" GroupName="a"></RadioButton>
        </StackPanel>
        <TextBox x:Name="tb_SFZH" Width="452" HorizontalAlignment="Left" Grid.Row="2" Grid.Column="1" Margin="9,0,0,0" />
        <TextBox x:Name="tb_JTDZ" Width="452" HorizontalAlignment="Left" Grid.Row="3" Grid.Column="1" Margin="9,0,0,0"/>
        <StackPanel Grid.Row="4" Orientation="Horizontal" Grid.Column="1" Margin="9,0">
            <Button Name="btnOK" Content="确定" Width="110" Click="btnOK_Click" Margin="10"/>
            <Button Name="btnNo" Content="查看列表" Width="110" Margin="10" Click="btnSearchList_Click"/>
        </StackPanel>
    </Grid>
</Window>

数据展示代码,说明:   xmlns:local="clr-namespace:WPF"是本项目中用来性别进行翻转的类,我们暂时把它作为页面的资源Window.Resources,在需要转换的属性设置如下: <DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="性别" Binding="{Binding p_sex, Converter={StaticResource vc} }" Width="80" />

<Window x:Class="WPF.DetilList"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPF"
        Title="通过传智播客Win8学习后-学生信息列表" FontSize="20" ResizeMode="NoResize" Height="300" Width="900">
    <Window.Resources>
        <local:ValueConverte x:Key="vc"/>
    </Window.Resources>
    <Grid Name="Layout" DataContext="{Binding}">
        <DataGrid HeadersVisibility="All" IsReadOnly="True" Name="dg_View" AutoGenerateColumns="False"  HorizontalAlignment="Left" VerticalAlignment="Top">
            <DataGrid.Columns>
                <DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="行号" Binding="{Binding p_rowIndex}" Width="60" />
                <DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="学号" Binding="{Binding p_id }" Width="100" />
                <DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="姓名" Binding="{Binding p_name }" Width="120" />
                <DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="性别" Binding="{Binding p_sex, Converter={StaticResource vc} }" Width="80" />
                <DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="身份证号" Binding="{Binding p_sfz }" Width="180" />
                <DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" Header="家庭地址" Binding="{Binding p_address }" Width="*" />
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

数据展示的后台代码:public DetilList(ObservableCollection<WPF.MainWindow.Student> oblist)
        {
            InitializeComponent();
            dg_View.ItemsSource = oblist;
            //Layout.DataContext = oblist;
            //dg_View.SetBinding(Grid.DataContextProperty, new Binding() { Source = Layout.DataContext });
        }

说明: Binding="{Binding p_id}" 绑定对象list单个对象的对应属性,其中有一个特别属性:性别,录入数据库是1,2,但是展示时是男女,这个翻转功能交给了ValueConverter类,它实现了IValueConverter,代码如下:

 public class ValueConverte : IValueConverter
    {
        /// <summary>
        /// 值转换为性别进行翻转
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <param name="parameter"></param>
        /// <param name="culture"></param>
        /// <returns></returns>
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string s = value.ToString();
            return "1".Equals(s) ? "男" : "女";
        }

      //因为数据绑定时有可能是双向绑定,即UI端改变的数据会影响到数据,也有可能需要将男女反向转会1,2,数据源默认是OneWay,所以此时不加逻辑代码
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

最后总结:本小程序的数据翻转,数据绑定是通过学习传智播客杨中科老师Win8开发视频中学习到的。

注:此项目参考"传智播客.net培训Windows 8开发视频教程")源码下载地址:https://files.cnblogs.com/AiPhone/VS2012.zip