如何在不选择的情况下从DataGrid复制所有单元格?

时间:2017-11-12 11:41:59

标签: c# wpf xaml datagrid

我在XAML代码下面有一个DataGrid:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding GetCar}" CanUserAddRows="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Id" Binding="{Binding Id, StringFormat={}{0:D8}}"/>
        <DataGridTextColumn Header="Brand" Binding="{Binding Brand}"/>
        <DataGridTextColumn Header="Model" Binding="{Binding Model}"/>
        <DataGridTextColumn Header="Year" Binding="{Binding Year}"/>
        <DataGridTextColumn Header="Color" Binding="{Binding Color}"/>
    </DataGrid.Columns>
</DataGrid>

C#代码:

public partial class Car
{
    public int Id { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public string Year { get; set; }
    public string Color { get; set; }
}

private IEnumerable<Car> car;

public IEnumerable<Car> GetCar
{
    get
    {
        car.Add(new Car {
            Id = 1,
            Brand = "Honda",
            Model = "Fit",
            BodyType = "Sedan",
            Color = "White",
            Condition = "Good",
            EngineCapacity = "1.5",
            Helm = "Right",
            Transmission = "Automatic",
            Year = "2004"
        });
        return car;
    }
}

实际上,数据来自数据库,并且有很多数据。它们已经分类。

还有一个Button,当按下时,DataGrid中的所有单元格都应该复制到剪贴板。

1 个答案:

答案 0 :(得分:0)

如果您想将carList复制到剪贴板并稍后获取,可以执行以下操作:

 var carList = new List<Car>()
 for(int i= 0;i<= dataGridView1.Rows-1;i++)
     {
        carList.Add(new Car
                      {
                        Id = dataGridView1.Rows[i].Cells[0].Value,
                        Brand = dataGridView1.Rows[i].Cells[1].Value,
                        Model = dataGridView1.Rows[i].Cells[2].Value,
                        Year = dataGridView1.Rows[i].Cells[3].Value,
                        Color = dataGridView1.Rows[i].Cells[4].Value
                });
} 
System.Windows.Forms.Clipboard.SetDataObject(carList);
var carListFromCB = System.Windows.Forms.Clipboard.GetDataObject().GetData(carList.GetType());

在WPF中获取Row内容:

public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
 {
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
      var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
                if (null != row) yield return row;
    }
 }

并致电GetDataGridRows,如:

 var rows = GetDataGridRows(datagrid1);

 foreach (DataGridRow r in rows)
 {
   Car carItem = r.Item as Car;
   carList.Add(carItem);
 }