WPF 应用开发记录

最近刚刚学习WPF, 搞了大约1个多星期。

以下是值得记录的point 

 

一、建立FRAME,使得navigation service 可以使用

 

setting up WPF application in vs2012 professional.

自带的mainwindow.xaml file 添加:

   

    



 

这样就可以在新添加的page里使用:

xxx page = new xxx();

NavigationService.Navigate(page);

进行换页。

 

二、建立数据库,连接到应用并使用LINQ

在server explorer里create new sql database

create new table1

然后将新建dbml 文件,拖拽table1到dbml视图内。即可建立连接。

在dbml.cs file 内添加

[Database]

    partial class XXXDataContext:DataContext

    {

    }

 

这样在其他文件中即可使用LINQ来访问数据库:

XXXDataContext db = new XXXDataContext();

var data = from r in db.table1.......

 

三、Parse CSV files

 

//open the csv file in windows and get path of it, then using streamReader to read it

 

private void _csv_upload_Click(object sender, RoutedEventArgs e)

        {

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            Nullable result = dlg.ShowDialog();

            TaxList _taxList = new TaxList();

 

            if (result == true)

            {

                // Open document

                _taxList.CreateTime = DateTime.Now;

 

                string path = dlg.FileName;

                string filename = System.IO.Path.GetFileName(path);

 

                _taxList.FileName = filename;

                _taxList.Id = userId;

                StreamReader streamRd = new StreamReader(path);

                NewCsvReader ncr = new NewCsvReader();

                ncr.GetHeader(streamRd, _taxList, db);

            }

 

            this._listTaxlist.ItemsSource = LoadCSVBoxListData();

 

        }

 

//NewCsvReader.cs

//使用了CsvHelper,在Nuget extension中搜索CvsHelper并添加

//6为目前csv file内field的个数

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using CsvHelper;

using System.IO;

 

namespace newtest1

{

    class NewCsvReader

    {

 

        public void GetHeader(StreamReader m, TaxList tlist, SalesDataContext db)

        {

 

            var csvRd = new CsvHelper.CsvReader(m);

            csvRd.Configuration.HasHeaderRecord = false;

            string ListName="";

            if(csvRd.Read())

                 ListName = csvRd.GetField(0);

            tlist.ListName = ListName;

 

            csvRd.Read();           

            string serialNum = csvRd.GetField(0);

            tlist.SerialNum = serialNum;

 

            csvRd.Read();

            string Notify = csvRd.GetField(0);

            tlist.Notify = Notify;

            db.TaxLists.InsertOnSubmit(tlist);

            db.SubmitChanges();                                      

            //finish dealing with taxlist table

 

             csvRd.Read();

              

            //begin reading the columHeaders

            int i=2;

            List<</span>string> TimeName= new List<</span>string>();

            while(i<6)

            {

 

                TimeName.Add(csvRd.GetField(i));

                i++;

            }

            i = i - 2;      //i is the num of months list in the file

 

            //begin reading the data

            while (csvRd.Read())

            {

                for (int j = 0; j < i; j++)

                {

                    TaxRow taxrow = new TaxRow();

 

                    taxrow.TaxListId = tlist.TaxListId;

                    taxrow.CreateTime = DateTime.Now;

                    string acc = csvRd.GetField(0).TrimStart("0".ToCharArray());

                    taxrow.AccountNum = acc;

                    taxrow.SiteNum = csvRd.GetField(1);

                    taxrow.TaxMoney = decimal.Parse(csvRd.GetField(j + 2).Replace("$", ""));

                    string timetemp = "01"+TimeName[j];

                    taxrow.Time = Convert.ToDateTime(timetemp);

 

                    db.TaxRows.InsertOnSubmit(taxrow);                    

                    db.SubmitChanges();

                }

            }

               

        }

    }

}

 

//注意:需要在dbml文件中选择table1 KeyId 的Property, 把Auto generated Value 设置为True

//否则会出现try to insert value into identical fields 类似的错误提醒

 

 

四、Parse txt files

 

//open the txt file in windows and get path of it, then using streamReader to read it

 

private void _txt_upload_Click(object sender, RoutedEventArgs e)

        {

            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();

            Nullable<</span>bool> result = dlg.ShowDialog();

            AddressList _addressList = new AddressList();

 

            if (result == true)

            {

                _addressList.CreateTime = DateTime.Now;

                string path = dlg.FileName;

 

                string filename = System.IO.Path.GetFileName(path);

                _addressList.FileName = filename;

                _addressList.ListName = filename.Replace(".txt", "");

                _addressList.Id = userId;

 

                db.AddressLists.InsertOnSubmit(_addressList);

                db.SubmitChanges();

                StreamReader streamRd = new StreamReader(path);

                ReadText readtext = new ReadText();

                readtext.LoadData(streamRd, _addressList);

            }

 

            this._listAddlist.ItemsSource = LoadAddBoxListData();

 

        }


 


//ReadText.cs


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace newtest1

{

    class ReadText

    {

        SalesDataContext db = new SalesDataContext();

 

        public void LoadData(StreamReader m, AddressList alist)

        {

 

            TextHelper txthlp = new TextHelper(m);

           

            while (txthlp.Read())

            {

                AddressRow arow = new AddressRow();

                arow.AddressListId = alist.AddressListId;

                string acct = txthlp.GetField(0).Replace("-","").TrimStart("0".ToCharArray());

                arow.AccountNum = acct;

                arow.SiteNum = txthlp.GetField(1);

                arow.Status = txthlp.GetField(2);

                arow.SICcode = txthlp.GetField(3);

                arow.CompanyName = txthlp.GetField(4);

                arow.Empty1 = txthlp.GetField(5);

                arow.PostBox = txthlp.GetField(7);

                arow.AddressStreet = txthlp.GetField(6);

                arow.City = txthlp.GetField(8);

                arow.State = txthlp.GetField(9);

                arow.ZipCode = txthlp.GetField(10);

                arow.Empty2 = txthlp.GetField(11);

 

                db.AddressRows.InsertOnSubmit(arow);

                db.SubmitChanges();

            }           

 

        }

    }

}

 


//self made textHelper.cs


//主要提供了GetField, Read()方法


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace newtest1

{

    class TextHelper

    {

        public StreamReader reader;

        public string TextLine;

        public TextHelper(StreamReader m)

        {

            reader = m;

        }

 

        public string GetField(int pos)

        {

            int i = pos + 1;

            string s = TextLine;

 

            int posend = 0;

            int postart = 0;

            for (int j = 0; j < s.Length; j++)

            {

                if (s[j] == ';')

                {

                    i--;

                    if (i < 1)

                    {

                        posend = j;

                        break;

                    }

                    else

                    {

                        postart = j + 1;

                    }

                }

            }

            return s.Substring(postart, posend - postart);

        }

 

        public bool Read()

        {

            if (reader.EndOfStream)

                return false;

            TextLine = reader.ReadLine();

            return true;

        }

 

        public int GetRows()

        {

           

            return reader.ReadToEnd().Split('\n').Length;

 

        }

    }

}

 


五、Display data in graphs in WPF app


使用了dynamic data display


下载地址:http://dynamicdatadisplay.codeplex.com/wikipage?title=D3v1


注意:需要手动右键选择dll files->property, 选择unblock,然后在add references


否则会遇到无法识别ChartPlotter等controls


需要添加的dll files:Dynamic Data Display, Dynamic Data Display.Control


 


在xaml文件中添加:


xmlns:d3=http://research.microsoft.com/DynamicDataDisplay/1.0


 


<</span>d3:ChartPlotter Name="plotter" Margin="10,10,20,10" >

            <</span>d3:ChartPlotter.HorizontalAxis>

                <</span>d3:HorizontalDateTimeAxis Name="dateAxis"ShowMayorLabels="False"/>

            </</span>d3:ChartPlotter.HorizontalAxis>

            <</span>d3:ChartPlotter.VerticalAxis>

                <</span>d3:VerticalAxis Name="countAxis"/>

            </</span>d3:ChartPlotter.VerticalAxis>

 

            <</span>d3:Header FontFamily="Arial" Content="Tax Money By Month"/>

            <</span>d3:VerticalAxisTitleFontFamily="Arial" Content="Money Sum"/>

            <</span>d3:HorizontalAxisTitleFontFamily="Arial" Content="Date"/>

        </</span>d3:ChartPlotter>


 


//xaml.cs file


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using Microsoft.Research.DynamicDataDisplay; // Core functionality

using Microsoft.Research.DynamicDataDisplay.DataSources; // EnumerableDataSource

using Microsoft.Research.DynamicDataDisplay.PointMarkers; // CirclePointMarker

using Microsoft.Research.DynamicDataDisplay.Charts.Navigation;

using System.IO;

using System.Collections;

 

namespace newtest1

{

    ///

    /// Interaction logic for Graph.xaml

    ///

    public partial class Graph : Page

    {

        SalesDataContext db = new SalesDataContext();

 

        public Graph(IList acclist)

        {

            InitializeComponent();

 

            int count = acclist.Count;

            LineAndMarker<</span>MarkerPointsGraph> chart;

 

            for (int i = 0; i < count; i++)

            {

                var firstAcc = acclist[i];

 

             //对于这个用了sum的group的LINQ语句还是研究了一阵的

             //这样就可以返回一定时间段的money的sum

 

                var money2 = (from m in db.TaxRows

                              orderby m.Time

                              where m.AccountNum == firstAcc.ToString()

                              group m by m.Time into g

                              select new

                              {

                                  Time = g.Key,

                                  TaxMoney = g.Sum(x => x.TaxMoney)

                              }).ToList();

 

                List<</span>double> tempmoney = new List<</span>double>();

                List<</span>DateTime> temptime = new List<</span>DateTime>();

                foreach (var r in money2)

                {

                    var num = (double)r.TaxMoney;

                    DateTime time = r.Time.Value;

                    tempmoney.Add(num);

                    temptime.Add(time);

                }

 

                var source = new EnumerableDataSource<</span>DateTime>(temptime);

                source.SetXMapping(x => dateAxis.ConvertToDouble(x));

                var source2 = new EnumerableDataSource<</span>double>(tempmoney);

                source2.SetYMapping(y => y);

                source2.AddMapping(ShapeElementPointMarker.ToolTipTextProperty, y => String.Format("Value is {0}",y));

 

 

                CompositeDataSource cmdc = new CompositeDataSource(source, source2);

                chart= plotter.AddLineGraph(cmdc,

                                     new Pen(Brushes.Blue, 2),

                                     new CirclePointMarker { Size = 10.0, Fill = Brushes.Red },

                                     new PenDescription("TaxMoneyAmount"));

 

 

                plotter.Children.Add(new CursorCoordinateGraph());

                chart.MarkerGraph.DataSource = cmdc;

               

 

            }

 

            plotter.Viewport.FitToView();

        }

    }

}

 


//ToolTipTextProperty 还有些问题,还没有继续研究下去。

 

以上流程仅供参考,由于刚刚起步就得停止,估计后续很难会有了。

但是还是学到了很多,以此记录下开发流程。

 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值