2014-02-16 177 views
4

我刚刚制作了一个C#控制台应用程序,它可以读取.csv文件并以整洁的方式将其写入控制台,但是现在我想让它进入WPF使它更加整洁。将.csv文件读入WPF应用程序(C#)

我以前的控制台应用程序是这样的:

class Program 
{ 
    static void Main(string[] args) 
    { 
     string[] tokens; 
     char[] separators = { ';' }; 
     string str = ""; 

     FileStream fs = new FileStream(@"D:\Dokumenter\Skole\6. semester\GUI\Exercises\Exercise2\02 deltagerliste.csv", 
             FileMode.Open); 
     StreamReader sr = new StreamReader(fs, Encoding.Default); 

     while ((str = sr.ReadLine()) != null) 
     { 
      tokens = str.Split(separators, StringSplitOptions.RemoveEmptyEntries); 

      Console.WriteLine(String.Format("{0,-20}", tokens[0]) + 
           String.Format("{0,-15}", tokens[1]) + 
           String.Format("{0,-15}", tokens[2]) + 
           String.Format("{0,-15}", tokens[3])); 
     } 

     Console.ReadLine();    
    } 
} 

它的伟大工程,但我必须承认,我有困难找到从哪里开始与WPF应用程序。

到目前为止,我已经想出了以下带有.csv文件的四个头文件的XAML代码(因为它有四列),我假设我必须找到一种方法将相应的行放入相应的列中。

<Window x:Class="WpfApplication1.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="Deltagerliste" Height="350" Width="525" WindowStartupLocation="CenterScreen" WindowState="Maximized" 
    Background="DeepPink" 
    > 
<ListView HorizontalAlignment="Left" Height="320" VerticalAlignment="Top" Width="517"> 
    <ListView.View> 
     <GridView> 
      <GridViewColumn Header="First name"/> 
      <GridViewColumn Header="Last name"/> 
      <GridViewColumn Header="ID"/> 
      <GridViewColumn Header="Email"/> 
     </GridView> 
    </ListView.View> 
</ListView> 

我的主要和最初的问题是我的文件到ListView如何阅读。我对C#和XAML都很陌生,尽管我很清楚如何在C#中打开和读取文件,但XAML中的语法对我来说有点困惑。

+1

你可能想阅读一些有关MVVM模式,数据绑定等 –

+0

您可以优化的String.Format代码:的String.Format(“{0,} -20 {1,-15} {2,-15} {3,-15}“,令牌[0],令牌[1],令牌[2],令牌[3])所以你不必连接4个字符串.formats – Measuring

回答

13

首先:创建一个将保存每行数据的类。

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public int ID { get; set; } 
    public string Email { get; set; } 

    public Person(string firstName, string lastName, int id, string email) 
    { 
     FirstName = firstName; 
     LastName = lastName; 
     ID = id; 
     Email = email; 
    } 
} 

然后创建将从CSV文件返回的人员名单功能:

public IEnumerable<Person> ReadCSV(string fileName) 
{ 
    // We change file extension here to make sure it's a .csv file. 
    // TODO: Error checking. 
    string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(fileName, ".csv")); 

    // lines.Select allows me to project each line as a Person. 
    // This will give me an IEnumerable<Person> back. 
    return lines.Select(line => 
    { 
     string[] data = line.Split(';'); 
     // We return a person with the data in order. 
     return new Person(data[0], data[1], Convert.ToInt32(data[2]), data[3]); 
    }); 
} 

然后用合适的绑定配置列表视图的列。 注意的X:名称属性的名称将使用形式的cs文件访问此列表视图:

<ListView x:Name="ListViewPeople"> 
    <ListView.View> 
     <GridView> 
      <GridViewColumn Header="First name" Width="100" DisplayMemberBinding="{Binding Path=FirstName}"/> 
      <GridViewColumn Header="Last name" Width="150" DisplayMemberBinding="{Binding Path=LastName}"/> 
      <GridViewColumn Header="ID" Width="40" DisplayMemberBinding="{Binding Path=ID}"/> 
      <GridViewColumn Header="Email" Width="200" DisplayMemberBinding="{Binding Path=Email}"/> 
     </GridView> 
    </ListView.View> 
</ListView> 

最后绑定列表视图的方法的ItemsSource返回的人名簿:

public MainWindow() 
{ 
    InitializeComponent(); 

    // We can access ListViewPeople here because that's the Name of our list 
    // using the x:Name property in the designer. 
    ListViewPeople.ItemsSource = ReadCSV("example"); 
} 

CSV文件

Henk;van Dam;1;[email protected] 
Alex;the Great;2;[email protected] 

最终的结果

Program result

+0

谢谢!您已经帮助我了解了很多代码!当我尝试初始化下面的代码(我认为它是ListViewPerson?)时出现以下错误:“名称'ListViewPerson'在当前上下文中不存在”。我已经将所有代码写入与MainWindow:Window类相同的xaml.cs文件中,但是它作为独立类和IEnumerable写入。尽管ListViewPerson.ItemsSource ...在MainWindow()函数中。 # 'ListViewPerson.ItemsSource = ReadCSV(@“D:\ Dokumenter \ Skole \ 6。semester \ GUI \ Exercises \ Exercise2 \ 02 deltagerliste.csv”);' – Left4Cookies

+0

@ Left4Cookies将ListView的Name属性更改为listViewPeople和你可以调用它。 – Measuring

+0

@ Left4Cookies你能勾选复选标记以将此答案标记为已接受吗?如果它不能解决你的问题,请告诉我。谢谢。 – Measuring