I am trying to make editable DataGridwith dynamic columns in a MVVM WPF project. Dynamic columns will be of the same type, i.e. decimal.
The goal is to assemble store departments with an unlimited number of departments. I tried to demonstrate this below.
Day Dept1 Dept2 Dept3... TotalOfDepartments CashTotal CreditTotal
1 100 200 50 350 50 300
2 75 100 0 175 25 150
So, there are numerous stores with uncertain departments, and my goal is to collect a month
I want to make editable departments, CashTotal and CreditTotal Columns. I had several approaches that I tried:
. :
:
public class DailyRevenues
{
public int ShopId { get; set; }
public int Day { get; set; }
public ObservableCollection<Department> DepartmentList { get; set; }
public DailyRevenues()
{
this.DepartmentList = new ObservableCollection<Department>();
}
}
public class Department
{
public string Name { get; set; }
private decimal total;
public decimal Total
{
get { return total; }
set { total = value; }
}
}
ViewModel:
public class DataItemViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public DataItemViewModel()
{
this.MonthlyRevenues = new ObservableCollection<DailyRevenues>();
var d1 = new DailyRevenues() { ShopId = 1, Day = 1 };
d1.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 100 });
d1.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 200 });
var d2 = new DailyRevenues() { ShopId = 1, Day = 2 };
d2.DepartmentList.Add(new Department() { Name = "Deapartment1", Total = 75 });
d2.DepartmentList.Add(new Department() { Name = "Deapartment2", Total = 150 });
d2.DepartmentList.Add(new Department() { Name = "Deapartment3", Total = 100 });
this.MonthlyRevenues.Add(d1);
this.MonthlyRevenues.Add(d2);
}
private ObservableCollection<DailyRevenues> monthlyRevenues;
public ObservableCollection<DailyRevenues> MonthlyRevenues
{
get { return monthlyRevenues; }
set
{
if (monthlyRevenues != value)
{
monthlyRevenues = value;
OnPropertyChanged(nameof(MonthlyRevenues));
}
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
XAML:
<DataGrid ItemsSource="{Binding MonthlyRevenues}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="Day" Binding="{Binding Path=Day}" />
<DataGridTextColumn Header="{Binding Path=MonthlyRevenues[0].DepartmentList[0].Name}" Binding="{Binding Path=DepartmentList[0].Total, Mode=TwoWay}" />
<DataGridTextColumn Header="{Binding Path=DepartmentList[1].Name}" Binding="{Binding Path=DepartmentList[1].Total, Mode=TwoWay}" />
<DataGridTextColumn Header="Department Total"/>
<DataGridTextColumn Header="Cash Total" />
<DataGridTextColumn Header="Credit Total" />
</DataGrid.Columns>
</DataGrid>
, XAML , - .
: ( ) shop1, / . , , , . , . Shop2 , .
EDIT 1: .