【发布时间】:2015-02-26 22:35:09
【问题描述】:
我正在用一个文件填充一个列表框。这可以通过两种方法来完成,由按下按钮启动的打开文件对话框命令和将操作拖放到列表框中。我想将文件路径(对于列表框中的文件)传递给我的代码的其他区域。比如读取列表框中文件的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");
}
【问题讨论】:
标签: c# wpf listbox datacontext