I can't reach to bind an object to a datagrid
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
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 a File
to DataGrid.ItemsSource
(indirectly through binding and DataContext
). But ItemsSource
needs a collection of items, not just one item.
If you change the second line in the event handler to:
this.dataGridElencoFiles.DataContext = new File[] { files };
the DataGrid
shows with some columns (like “Percorso” or “NomeFile”), but prints only “(Collection)” in each of them. The DataGrid
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 your File
class to something like Directory
and add a method that returns collection of files from it. Or implement IEnumerable<your_file_class>
.
精彩评论