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

时间:2015-02-26 22:35:09

标签: 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)

请参阅以下代码。

<StackPanel>            
        <ListBox x:Name="fileList" Height="100" Drop="fileList_Drop" DisplayMemberPath="Name" AllowDrop="True"/>
        <Button Content="Browse" Click="Button_Click"/>
        <Rectangle/>
    </StackPanel>
 public partial class MainWindow : Window
{
    ObservableCollection<FileInfo> lst = new ObservableCollection<FileInfo>();
    public MainWindow()
    {
        InitializeComponent();
        fileList.ItemsSource = lst;

    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
        if ((bool)dlg.ShowDialog())
        {
            FileInfo fi= new FileInfo(dlg.FileName);
            lst.Add(fi);
        }
    }

    private void fileList_Drop(object sender, DragEventArgs e)
    {
        string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];

        foreach (string droppedFilePath in droppedFilePaths)
        {
            FileInfo fi = new FileInfo(droppedFilePath);
            lst.Add(fi);
        }
    }
}