将文件路径从列表框中的文件传递到dataconext C#

时间:2015-03-10 23:48:58

标签: c# wpf listbox datacontext

我正在用文件填充列表框。这可以通过两种方法完成,即按下按钮启动的打开文件对话框命令以及拖放到列表框中的拖放操作。我想将文件路径(对于列表框中的文件)传递给我的代码的其他区域,例如读取列表框中文件的DataContext。基本上我希望文件路径在填充列表框时自动更新。我是C#的新手,很抱歉,如果我没有正确解释自己或提供足够的信息。填充我的列表框(名为FilePathBox)和'运行'按钮如下:

private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
    var openFileDialog = new Microsoft.Win32.OpenFileDialog();
    //openFileDialog.Multiselect = true;
    openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
    openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

    if (openFileDialog.ShowDialog())
    {
        FilePathBox.Items.Clear();

        foreach (string filename in openFileDialog.FileNames)
        {
            ListBoxItem selectedFile = new ListBoxItem();

            selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
            selectedFile.ToolTip = filename;                    
            FilePathBox.Items.Add(selectedFile);
        }
    }          
}


private void FilesDropped(object sender, DragEventArgs e)
{
     if (e.Data.GetDataPresent(DataFormats.FileDrop))
     {
        FilePathBox.Items.Clear();

        string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];

        foreach (string droppedFilePath in droppedFilePaths)
        {
            ListBoxItem fileItem = new ListBoxItem();

            fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
            fileItem.ToolTip = droppedFilePath;
            FilePathBox.Items.Add(fileItem);
        }
    }  
}

private void RunButton_Click(object sender, RoutedEventArgs e)
{
    DataContext = OldNewService.ReadFile(@"C:\Users\Documents\Lookup Table.csv");
}

1 个答案:

答案 0 :(得分:0)

我添加了评论,但是我认为在单击RunButton时需要一种方法来获取所选文件路径,所以只需将其添加到RunButton_Click方法中,

private void RunButton_Click(object sender, RoutedEventArgs e)
{
  string selection = (string)FilePathBox.SelectedItem;
  DataContext = OldNewService.ReadFile(selection);
}