我有片段代码来执行以下操作:
- 将两个ListBox绑定在一起。第一个显示目录,第二个显示子文件夹 -DataGridView显示.bmp文件。
我只需要设置一个名为(Blocks)的列,并添加双击事件以插入dwg文件。
public partial class Form1 : Form
{
private string rootDirectory = @"D:\test\Blocks";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.DataSource = Directory.GetDirectories(rootDirectory).Select(Path.GetFileName).ToList();
listBox1.SelectedIndexChanged += ListBox1_SelectedIndexChanged;
listBox2.SelectedIndexChanged += ListBox2_SelectedIndexChanged;
DataGridViewImageColumn dgvimgcol = new DataGridViewImageColumn();
dgvimgcol.ImageLayout = DataGridViewImageCellLayout.Stretch;
dgvimgcol.Width = 250;
dgvimgcol.HeaderText = "Blocks";
dgvimgcol.Image = null;
dataViewImages.RowTemplate.Height = 300;
dataViewImages.Columns.Add(dgvimgcol);
dataViewImages.AllowUserToAddRows = false;
dataViewImages.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// When an item changes in the first listbox, update the second listbox datasource
var parentDir = Path.Combine(rootDirectory, listBox1.SelectedItem.ToString());
listBox2.DataSource = Directory.GetDirectories(parentDir).Select(Path.GetFileName).ToList();
}
private void ListBox2_SelectedIndexChanged(object sender, EventArgs e)
{
// When an item changes in the second listbox, update the datagridview datasource
var parentDir = Path.Combine(rootDirectory, listBox1.SelectedItem.ToString(),
listBox2.SelectedItem.ToString());
dataViewImages.DataSource = Directory.GetFiles(parentDir).Select(f => new { FileName = Path.GetFileName(f) }).ToList();
}
}
答案 0 :(得分:1)
Here is a demo I created for you on Github
为简单起见,我只演示了如何创建自定义类型的绑定列表,其中包含类型为Image
的属性,网格将知道如何显示。图像存储在项目中。
视图模型有两个属性:
using System.Drawing;
namespace ImageGrid
{
class FilesViewModel
{
public string FileName { get; set; }
public Image Picture { get; set; }
}
}
表单包含用于创建视图模型的列表(具体来说,我正在使用BindingList)的代码。它读取“images”文件夹中的所有文件,并为每个文件构建一个新实例,为System.Drawing.Image
属性创建Picture
。
最后,它将网格的DataSource
设置为列表:
private void Form1_Load(object sender, EventArgs e)
{
BindingList<FilesViewModel> vmList = new BindingList<FilesViewModel>();
string[] theFiles = Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "images"));
foreach (string f in theFiles)
{
Image img = Image.FromFile(f);
vmList.Add(new FilesViewModel { FileName = Path.GetFileName(f), Picture = img });
}
dataGridView1.DataSource = vmList;
}