I've been working on this little program, that needs to take file inputs of CSV files, store them in a listbox, and then update automatically the datagrid. When there is added more files, the datagrid needs to expand with the new file data and add next to it.
- What works is adding files to the listbox with the binding in the XAML code and codebehind.
- What doesn't work is merging the data to display dynamically with the binding to the datagrid. Property changed are raised, but grid aren't updating.
In DataGridViewModel is where my csv merge code is:
public class DataGridViewModel
{
static public DataGridModel _dataGridModel = new DataGridModel();
public static void ReturnDataTableForGridView()
{
DataTable mainTable = new DataTable();
//-- #3 Test merge
foreach (var item in SidePanelViewModel.GetPathFileList())
{
DataTable dataTable = new DataTable();
try
{
string[] Lines = File.ReadAllLines(item.Filepath);
string[] Fields;
Fields = Lines[0].Split(new char[] { ';' });
int Cols = Fields.GetLength(0);
//1st row skal være kolonne navn;
for (int X = 0; X < Cols; X++)
dataTable.Columns.Add(Fields[X].ToLower(), typeof(string));
DataRow Row;
for (int T = 1; T < Lines.GetLength(0); T++)
{
Fields = Lines[T].Split(new char[] { ';' });
Row = dataTable.NewRow();
for (int f = 0; f < Cols; f++)
Row[f] = Fields[f];
dataTable.Rows.Add(Row);
}
//-- Merges every files(tables) into one.
mainTable.Merge(dataTable);
}
catch (Exception)
{
return null;
}
}
//-- Sets the datatablemerger which raises the propertychanged
_dataGridModel.DatatableMerger = mainTable;
}
}
The DataGridModel class
public class DataGridModel : INotifyPropertyChanged
{
DataTable _dataTableMerger { get; set; } = new DataTable();
public DataTable DatatableMerger
{
get
{
return _dataTableMerger;
}
set
{
_dataTableMerger = value;
OnPropertychanged("DatatableMerger");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertychanged([CallerMemberName] string caller = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(caller));
}
}
The dataGridview class
public DataGridView()
{
InitializeComponent();
}
The XAML code:
<DataGrid x:Name="MainDataGrid" Grid.Row="1" VerticalAlignment="Stretch" Height="auto" ItemsSource="{Binding Path=DatatableMerger, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}" >
</DataGrid>
</Grid>
<UserControl.DataContext>
<Model:DataGridModel/>
</UserControl.DataContext>
Currently output:
Wished output: