【问题标题】:Pass file path from file in listbox to dataconext C#将列表框中文件的文件路径传递给dataconext C#
【发布时间】:2015-03-10 23:48:57
【问题描述】:

我正在用一个文件填充一个列表框。这可以通过两种方法来完成,由按下按钮启动的打开文件对话框命令和将操作拖放到列表框中。我想将文件路径(对于列表框中的文件)传递到我的代码的其他区域,例如读取列表框中文件的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");
}

【问题讨论】:

  • 切换到真正的 MVVM,这段代码会更好地运行并且更有意义。为什么你甚至在没有 MVVM 的情况下为数据上下文而烦恼,这超出了我的理解。
  • 您是使用一个文件路径还是多个文件填充列表框,您似乎正在填充多个文件,因此您可能需要一个 selectedIndexChanged 侦听器来提供列表框中的选择,如果您这样做的话需要,我可以给你举个例子
  • 嗨 BradleyDotNET,你有没有链接到某个地方我可以了解更多关于你的建议。我对此很陌生,并且在没有太多指导的情况下一直在自学。任何建议将不胜感激。

标签: c# wpf listbox datacontext


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2018-12-26
    相关资源
    最近更新 更多