我对 WPF 相当陌生,想知道是否有可能将 WPF DataGrid 简单地导出到 csv 文件。我尝试使用反射来获取所需的值,尽管这在某种程度上有效我想知道是否可以使用附加属性来获取显示的值,这些不一定对应于项目源的值。只要我使用静态字符串或字符串的静态资源等,下面的附加属性就可以工作。如果我尝试使用列绑定(bind),我只会得到默认的 string.empty
public static readonly DependencyProperty ExportStringProperty =
DependencyProperty.RegisterAttached("ExportString", //name of attached property
typeof(string), //type of attached property
typeof(ExportBehaviour), //type of this owner class
new PropertyMetadata(string.Empty)); //the default value of the attached property
public static string GetExportString(DataGridColumn column)
{
return (string)column.GetValue(ExportStringProperty);
}
public static void SetExportString(DataGridColumn column, string value)
{
column.SetValue(ExportStringProperty, value);
}
是否有类似的方法可以通过以下方式从 xaml 获取绑定(bind)值:
<DataGridTextColumn Header="Name" Binding="{Binding (datagridexcel:Product.Name)}" datagridexcel:ExportBehaviour.ExportString="{Binding (datagridexcel:Product.Name)}"/>
如前所述,上面的内容适用于静态类型的字符串,而不适用于绑定(bind)。
必须说,在这种情况下应该避免使用项目源,我唯一感兴趣的是数据网格和那里显示的值。
最佳答案
我制作了这个简单的应用程序来演示从 DataGrid
获取 CSV 的方法。 .
您有 DataGrid
:
<DataGrid x:Name="MyDataGrid" Grid.Row="0" ItemsSource="{Binding Rows}" />
在此示例中,它绑定(bind)到 View 模型中的以下属性:
private IEnumerable<RowViewModel> _rows;
public IEnumerable<RowViewModel> Rows
{
get { return _rows; }
set
{
_rows = value;
OnPropertyChanged("Rows");
}
}
行设置为以下示例数据:
Rows = new List<RowViewModel>
{
new RowViewModel { FirstName = "John", LastName = "Doe", DateOfBirth = new DateTime(1988, 12, 19) },
new RowViewModel { FirstName = "Lara", LastName = "Croft", DateOfBirth = new DateTime(1975, 5, 3) },
new RowViewModel { FirstName = "Sam", LastName = "Fisher", DateOfBirth = new DateTime(1967, 2, 9) }
};
下
DataGrid
我有一个 Button
:<Button Grid.Row="1" Content="Copy values as CSV" Command="{Binding CopyAsCsvCommand}" CommandParameter="{Binding ElementName=MyDataGrid}" />
它绑定(bind)到
Command
在 View 模型和 CommandParameter
是整个DataGrid
.CopyAsCsvCommand = new DelegateCommand<DataGrid>(CopyAsCsvHandler);
Command
的处理方法,实际复制发生的地方:private void CopyAsCsvHandler(DataGrid dg)
{
dg.SelectAllCells();
dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dg);
dg.UnselectAllCells();
LivePreviewText = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
}
这相当于使用 CTRL+A 选择所有单元格并按 CTRL+C。
例子
现在您有了 CSV 内容,您可以将其保存到具有 CSV 扩展名的文件中。我希望这会有所帮助,这就是您要寻找的。
关于c# - WPF DataGrid 到 csv,只导出网格中的可见值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34704314/