【问题标题】:How to use OpenFileDialog in Wpf如何在 Wpf 中使用 OpenFileDialog
【发布时间】:2019-01-06 13:31:43
【问题描述】:

我正在使用 WPF 应用程序。我是 wpf 的新手,但我有使用 Windows 窗体的经验。 Wpf 很棒,我想学习如何使用它进行编程。我的问题是:我已经编写了一个代码,我可以使用它,但我无法正确使用 OpenFileDialog 函数。我想读取一个 csv txt 文件,文件的结构总是相同的,只是行不同。文件的名称也不同,我想一个接一个地读取和编辑文件。阅读、编辑、保存。我的代码在这里:

public static class PersonService

public static List<Person> ReadFile(string filepath)
{
    var lines = File.ReadAllLines(filepath);

    var data = from l in lines.Skip(1)
               let split = l.Split(';')
               select new Person
               {
                   Id = int.Parse(split[0]),
                   Name = split[1],
                   Age = int.Parse(split[2]),
                   Gender = (Gender)Enum.Parse(typeof(Gender), split[3])
               };

    return data.ToList();
}

}

公共部分类 Window2 : Window

public Window2()
{
    InitializeComponent();

OpenFileDialog csv = 新的 OpenFileDialog DataContext = PersonService.ReadFile(csv);

<Window x:Class="WpfApplication14.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window2" Height="300" Width="300">
<DataGrid AutoGenerateColumns="True"
          ItemsSource="{Binding}"/>

【问题讨论】:

标签: wpf


【解决方案1】:

这应该看起来像这样:

//Create file dialog and configure to open csv files only
OpenFileDialog csvFielDialog = new OpenFileDialog();
csvFielDialog.Filter = "CSF files(*.csv)|*.csv";

//Show the dialog to the user
bool? result = csvFielDialog.ShowDialog();

//If the user selected something perform the actions with the file
if(result.HasValue && result.Value)
{
    DataContext = PersonService.ReadFile(csvFielDialog.FileName);
}

【讨论】:

    猜你喜欢
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 2019-05-29
    • 2021-01-14
    • 2016-02-17
    相关资源
    最近更新 更多