我无法将对象绑定到数据网格
我是 WPF 和 c# 的初学者。
我有一个简单的 WPF 应用程序,其中有一个数据网格。我想在单击按钮时填充它:
private void buttonTest_Click(object sender, RoutedEventArgs e)
{
File files = new File(this.textBoxScegliSorgente.Text, datePicker.SelectedDate.Value);
this.dataGridElencoFiles.DataContext = files;
}
文件类是这样的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
namespace ArchiviazioneVecchiDocumenti
{
public class File
{
private List<string> percorso = new List<string>();
public List<string> Percorso
{ get { return percorso; } }
private List<string> nomeFile = new List<string>();
public List<string> NomeFile
{ get { return nomeFile; } }
private List<DateTime> dataUltimaModifica = new List<DateTime>();
public List<DateTime> DataUltimaModifica
{ get { return dataUltimaModifica; } }
private List<DateTime> dataUltimoAccesso = new List<DateTime>();
public List<DateTime> DataUltimoAccesso
{ get { return dataUltimoAccesso; } }
private List<long> dimensione = new List<long>();
public List<long> Dimensione
{ get { return dimensione; } }
private List<string> logErrori = new List<string>();
public List<string> LogErrori
{ get { return logErrori; } }
/* campi recuperati provvisori */
private DirectoryInfo sorgente;
private DirectoryInfo destinazione;
private DateTime data;
private string radioscelta;
private bool test;
private DirectoryInfo[] directories;
private FileInfo[] filesInDir;
private WshShellClass WshShell;
public File(string sorgente, DateTime data)
{
this.sorgente = new DirectoryInfo(sorgente);
this.data = data;
this.test = true;
ExploreDirectory(this.sorgente);
}
private void ExploreDirectory(DirectoryInfo dir)
{
try
{
this.filesInDir = dir.GetFiles();
}
catch (Exception e)
{
this.logErrori.Add(e.Message[0].ToString());
}
foreach (FileInfo file in filesInDir)
{
if (file.Extension != ".lnk")
{
if (file.LastWriteTime < this.data)
{
if (this.test == true)
{
try
{
List<string> veraPathLunga = new List<string>();
veraPathLunga.Add(dir.Name + "\\");
DirectoryInfo temp = dir;
while (temp.Name != this.sorgente.Name)
{
veraPathLunga.Add(temp.Parent.ToString() + "\\");
temp = temp.Parent;
}
veraPathLunga.Reverse();
veraPathLunga[0] = this.sorgente.FullName;
string percorsoFileUnito = string.Join("", veraPathLunga.ToArray());
this.percorso.Add(percorsoFileUnito);
this.nomeFile.Add(file.Name);
this.dimensione.Add(file.Length);
this.dataUltimaModifica.Add(file.LastWriteTime);
this.dataUltimoAccesso.Add(file.LastAccessTime);
}
catch (Exception e)
{
this.logErrori.Add(e.Message[0].ToString());
}
}
}
}
}
try
{
this.directories = dir.GetDirectories();
}
catch (Exception e)
{
this.logErrori.Add(dir.Name + " " + e.Message[0].ToString());
}
foreach (DirectoryInfo newDir in this.directories)
{
ExploreDirectory(newDir);
}
}
}
}
这是 XAML
<Window x:Class="ArchiviazioneVecchiDocumenti.Principale"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:app="clr-namespace:ArchiviazioneVecchiDocumenti"
xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Principale" Height="600" Width="800" >
<Window.Resources>
<!--<ObjectDataProvider x:Key="filesWpf" ObjectType="{x:Type app:File}"/>
<app:File x:Key="fileBinding"/>-->
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0">
<ToolBarTray DockPanel.Dock="Top" Background="LightGray">
<ToolBar Name="ButtonBar" Band="0" BandIndex="0" >
<Grid VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Height="23" Name="buttonSceglisorgente" Click="buttonScegliSorgente_Click" ToolTip="scegli la cartella o il disco locale in cui vuoi cercare i files da archiviare." Grid.Row="0" Grid.Column="0">Scegli cartella Sorgente</Button>
<TextBox Height="23" Name="textBoxScegliSorgente" Width="334" Grid.Row="0" Grid.Column="1" ToolTip="scegli la cartella o il disco locale in cui vuoi cercare i files da archiviare." IsEnabled="False"/>
<Button Height="23" Name="buttonScegliCestino" Click="buttonScegliCestino_Click" ToolTip="Scegli la cartella in cuo vuoi mettere i files obsoleti." Grid.Row="1" Grid.Column="0">Scegli cartella Destinazione</Button>
<TextBox Height="23" Name="textBoxSelectCestino" Width="334" Grid.Row="1" Grid.Column="1" ToolTip="Scegli la cartella in cuo vuoi mettere i files obsoleti." IsEnabled="False"/>
</Grid>
</ToolBar>
<ToolBar Name="kk" Band="0">
<Grid VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<my:DatePicker Height="25" HorizontalAlignment="Center" Name="datePicker" Width="130" Grid.Row="0" Grid.Column="0"/>
<StackPanel Grid.Row="1" Grid.Column="0">
<RadioButton IsChecked="True" Name="radioButtonAccesso" ToolTip="Archiviazione in base alla data dell'ultimo accesso al file." >Data Ultimo Accesso</RadioButton>
<RadioButton Name="radioButtonModifica" ToolTip="Archiviazione in base alla data dell'ultima modifica." >Data Ultima Modifica</RadioButton>
</StackPanel>
<Button Height="30" Width="60" Name="buttonTest" ToolTip="Esegui un test per vedere quanti files puoi archiviare" Grid.Row="0" Grid.Column="1" Click="buttonTest_Click">Test</Button>
<Button Height="30" Width="60" ToolTip="Procedi all'archiviazione dei vecchi documenti." Grid.Row="1" Grid.Column="1" Click="buttonProcedi_Click">Procedi</Button>
</Grid>
</ToolBar>
</ToolBarTray>
</DockPanel>
<TabControl Name="tabControl1" Grid.Row="1" Margin="0,10,0,0">
<TabItem Header="Elenco Files" Name="tabelencoFile">
<Grid>
<!--<my:DataGrid ItemsSource="{Binding Source={StaticResource fileBinding}}" HorizontalAlignment="Stretch" Margin="5" Name="dataGridElencoFiles" >-->
<my:DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" HorizontalAlignment="Stretch" Margin="5" Name="dataGridElencoFiles" >
<!--<my:DataGrid.Columns>
<my:DataGridTextColumn Header="Percorso" Width="SizeToCells" Binding="{Binding Percorso}" IsReadOnly="True"/>
<my:DataGridTextColumn Header="Nome File" Width="SizeToCells" Binding="{Binding NomeFile}" IsReadOnly="True"/>
</my:DataGrid.Columns>-->
</my:DataGrid>
</Grid>
</TabItem>
<TabItem Header="Elenco Errori" Name="tabElencoErrori">
<Grid>
<my:DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="5" Name="dataGridElencoErrori" />
</Grid>
</TabItem>
<TabItem Header="Log" Name="tabLog">
<Grid>
<my:DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="5" Name="dataGridLog" />
</Grid>
</TabItem>
</TabControl>
</Grid>
</Window>
任何人都可以帮我吗?
谢谢
I'm a begginer in WPF and c#.
I have a simple WPF application in which there is a datagrid. I want to populate it when I click a button:
private void buttonTest_Click(object sender, RoutedEventArgs e)
{
File files = new File(this.textBoxScegliSorgente.Text, datePicker.SelectedDate.Value);
this.dataGridElencoFiles.DataContext = files;
}
The File Class is this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.AccessControl;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
namespace ArchiviazioneVecchiDocumenti
{
public class File
{
private List<string> percorso = new List<string>();
public List<string> Percorso
{ get { return percorso; } }
private List<string> nomeFile = new List<string>();
public List<string> NomeFile
{ get { return nomeFile; } }
private List<DateTime> dataUltimaModifica = new List<DateTime>();
public List<DateTime> DataUltimaModifica
{ get { return dataUltimaModifica; } }
private List<DateTime> dataUltimoAccesso = new List<DateTime>();
public List<DateTime> DataUltimoAccesso
{ get { return dataUltimoAccesso; } }
private List<long> dimensione = new List<long>();
public List<long> Dimensione
{ get { return dimensione; } }
private List<string> logErrori = new List<string>();
public List<string> LogErrori
{ get { return logErrori; } }
/* campi recuperati provvisori */
private DirectoryInfo sorgente;
private DirectoryInfo destinazione;
private DateTime data;
private string radioscelta;
private bool test;
private DirectoryInfo[] directories;
private FileInfo[] filesInDir;
private WshShellClass WshShell;
public File(string sorgente, DateTime data)
{
this.sorgente = new DirectoryInfo(sorgente);
this.data = data;
this.test = true;
ExploreDirectory(this.sorgente);
}
private void ExploreDirectory(DirectoryInfo dir)
{
try
{
this.filesInDir = dir.GetFiles();
}
catch (Exception e)
{
this.logErrori.Add(e.Message[0].ToString());
}
foreach (FileInfo file in filesInDir)
{
if (file.Extension != ".lnk")
{
if (file.LastWriteTime < this.data)
{
if (this.test == true)
{
try
{
List<string> veraPathLunga = new List<string>();
veraPathLunga.Add(dir.Name + "\\");
DirectoryInfo temp = dir;
while (temp.Name != this.sorgente.Name)
{
veraPathLunga.Add(temp.Parent.ToString() + "\\");
temp = temp.Parent;
}
veraPathLunga.Reverse();
veraPathLunga[0] = this.sorgente.FullName;
string percorsoFileUnito = string.Join("", veraPathLunga.ToArray());
this.percorso.Add(percorsoFileUnito);
this.nomeFile.Add(file.Name);
this.dimensione.Add(file.Length);
this.dataUltimaModifica.Add(file.LastWriteTime);
this.dataUltimoAccesso.Add(file.LastAccessTime);
}
catch (Exception e)
{
this.logErrori.Add(e.Message[0].ToString());
}
}
}
}
}
try
{
this.directories = dir.GetDirectories();
}
catch (Exception e)
{
this.logErrori.Add(dir.Name + " " + e.Message[0].ToString());
}
foreach (DirectoryInfo newDir in this.directories)
{
ExploreDirectory(newDir);
}
}
}
}
This is the XAML
<Window x:Class="ArchiviazioneVecchiDocumenti.Principale"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:app="clr-namespace:ArchiviazioneVecchiDocumenti"
xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Principale" Height="600" Width="800" >
<Window.Resources>
<!--<ObjectDataProvider x:Key="filesWpf" ObjectType="{x:Type app:File}"/>
<app:File x:Key="fileBinding"/>-->
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DockPanel Grid.Row="0">
<ToolBarTray DockPanel.Dock="Top" Background="LightGray">
<ToolBar Name="ButtonBar" Band="0" BandIndex="0" >
<Grid VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<Button Height="23" Name="buttonSceglisorgente" Click="buttonScegliSorgente_Click" ToolTip="scegli la cartella o il disco locale in cui vuoi cercare i files da archiviare." Grid.Row="0" Grid.Column="0">Scegli cartella Sorgente</Button>
<TextBox Height="23" Name="textBoxScegliSorgente" Width="334" Grid.Row="0" Grid.Column="1" ToolTip="scegli la cartella o il disco locale in cui vuoi cercare i files da archiviare." IsEnabled="False"/>
<Button Height="23" Name="buttonScegliCestino" Click="buttonScegliCestino_Click" ToolTip="Scegli la cartella in cuo vuoi mettere i files obsoleti." Grid.Row="1" Grid.Column="0">Scegli cartella Destinazione</Button>
<TextBox Height="23" Name="textBoxSelectCestino" Width="334" Grid.Row="1" Grid.Column="1" ToolTip="Scegli la cartella in cuo vuoi mettere i files obsoleti." IsEnabled="False"/>
</Grid>
</ToolBar>
<ToolBar Name="kk" Band="0">
<Grid VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<my:DatePicker Height="25" HorizontalAlignment="Center" Name="datePicker" Width="130" Grid.Row="0" Grid.Column="0"/>
<StackPanel Grid.Row="1" Grid.Column="0">
<RadioButton IsChecked="True" Name="radioButtonAccesso" ToolTip="Archiviazione in base alla data dell'ultimo accesso al file." >Data Ultimo Accesso</RadioButton>
<RadioButton Name="radioButtonModifica" ToolTip="Archiviazione in base alla data dell'ultima modifica." >Data Ultima Modifica</RadioButton>
</StackPanel>
<Button Height="30" Width="60" Name="buttonTest" ToolTip="Esegui un test per vedere quanti files puoi archiviare" Grid.Row="0" Grid.Column="1" Click="buttonTest_Click">Test</Button>
<Button Height="30" Width="60" ToolTip="Procedi all'archiviazione dei vecchi documenti." Grid.Row="1" Grid.Column="1" Click="buttonProcedi_Click">Procedi</Button>
</Grid>
</ToolBar>
</ToolBarTray>
</DockPanel>
<TabControl Name="tabControl1" Grid.Row="1" Margin="0,10,0,0">
<TabItem Header="Elenco Files" Name="tabelencoFile">
<Grid>
<!--<my:DataGrid ItemsSource="{Binding Source={StaticResource fileBinding}}" HorizontalAlignment="Stretch" Margin="5" Name="dataGridElencoFiles" >-->
<my:DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True" HorizontalAlignment="Stretch" Margin="5" Name="dataGridElencoFiles" >
<!--<my:DataGrid.Columns>
<my:DataGridTextColumn Header="Percorso" Width="SizeToCells" Binding="{Binding Percorso}" IsReadOnly="True"/>
<my:DataGridTextColumn Header="Nome File" Width="SizeToCells" Binding="{Binding NomeFile}" IsReadOnly="True"/>
</my:DataGrid.Columns>-->
</my:DataGrid>
</Grid>
</TabItem>
<TabItem Header="Elenco Errori" Name="tabElencoErrori">
<Grid>
<my:DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="5" Name="dataGridElencoErrori" />
</Grid>
</TabItem>
<TabItem Header="Log" Name="tabLog">
<Grid>
<my:DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="5" Name="dataGridLog" />
</Grid>
</TabItem>
</TabControl>
</Grid>
</Window>
Can anyone give me a hand?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
旁注:如果您仅发布与您的问题相关的代码,那就太好了。 (OTOH太多代码总比太少好。)
您将
files
(这是一个File
)分配给DataGrid.ItemsSource
(间接通过绑定和 DataContext)。但是ItemsSource
需要一组项目,而不仅仅是一个项目。如果将事件处理程序中的第二行更改为:
DataGrid
显示一些列(如“Percorso”或“NomeFile”),但在每个列中仅打印“(Collection)”。DataGrid
无法将其显示为表格格式,因为每个集合可能具有不同的长度,并且没有迹象表明它们是相关的。相反,您应该有一个代表一个文件的类,并将这些文件的列表提供给 DataGrid。我会将您的
File
类重命名为Directory
之类的名称,并添加一个从中返回文件集合的方法。或者实现IEnumerable
。Side note: It would be great if you posted only code relevant to your question. (OTOH too much code is better than too little.)
You're assigning
files
which is aFile
toDataGrid.ItemsSource
(indirectly through binding andDataContext
). ButItemsSource
needs a collection of items, not just one item.If you change the second line in the event handler to:
the
DataGrid
shows with some columns (like “Percorso” or “NomeFile”), but prints only “(Collection)” in each of them. TheDataGrid
can't show that formatted as a table, because each of those collections could have different length and there is no indication that they are related.Instead, you should have a class that represents one file and give list of those to the
DataGrid
. I would rename yourFile
class to something likeDirectory
and add a method that returns collection of files from it. Or implementIEnumerable<your_file_class>
.