获取GridView的内容
本文关键字:GridView 获取 | 更新日期: 2023-09-27 18:06:00
我有一个应用程序c#/WPF与ListView包含GridView。我想让内容创建一个具有所有值的CSV文件。
我已经做了一些研究,但我只找到了windows窗体或WPF DataGrid的解决方案。
我的列表:
<ListView Grid.Row="1" x:Name="myListView"
BorderBrush="White" HorizontalAlignment="Stretch"
ItemsSource="{Binding Path=myItem}" SelectedItem="{Binding Path=ActualItem}">
<ListView.View>
<GridView x:Name="myGridView">
<GridViewColumn Header="{x:Static p:Resources.NAME}"
DisplayMemberBinding="{Binding Path=Name,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"
Width="{StaticResource doubleNaN}"/>
<GridViewColumn Header="{x:Static p:Resources.LABEL}"
DisplayMemberBinding="{Binding Path=Label,Mode=OneWay,UpdateSourceTrigger=PropertyChanged}"/>
</GridView>
</ListView.View>
</ListView>
我可以得到标题,但没有内容:
System.Text.StringBuilder csv = new System.Text.StringBuilder();
String separator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
foreach (System.Windows.Controls.GridViewColumn col in myGridView.Columns)
{
string header = col.Header as String;
if (!String.IsNullOrWhiteSpace(header))
{
csv.Append(header + separator);
}
}
csv.AppendLine();
System.IO.File.WriteAllText(path, csv.ToString());
如何获取CSV文件的内容
我找到了一个解决方案,也许不是最好的,但它有效。
问题是:
-
从GridView获取报头,因为报头取决于语言
-
只显示列
GridView中的项是tyep MyItem
,列包含属性。我创建了一个循环来获取标题和属性绑定它从GridView
。第二个循环从ListView
System.Text.StringBuilder csv = new System.Text.StringBuilder();
String separator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
List<String> listProperties = new List<string>();
csv.AppendLine("sep=" + separator);
foreach (System.Windows.Controls.GridViewColumn col in myGridView.Columns)
{
// Check if column is displayed
if (col.ActualWidth > 0)
{
// Get Header value
string header = col.Header as String;
//Check if Header is not empty
if (!String.IsNullOrWhiteSpace(header))
{
// Write in firte line
csv.Append(header + separator);
// Get if columns is binding a property
System.Windows.Data.Binding binding = col.DisplayMemberBinding as System.Windows.Data.Binding;
if (binding != null)
{
// Get the name of property
listProperties.Add(binding.Path.Path);
}
}
}
}
// Write first line
csv.AppendLine();
foreach (myItem item in myListView.Items)
{
foreach (String property in listProperties)
{
// Get and write value for property
object value = GetPropValue(item, property);
csv.Append(value + separator);
}
csv.AppendLine();
}
System.IO.File.WriteAllText(path, csv.ToString());
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}