使用DataGrid
方法将数据绑定到MVVM
时遇到麻烦。可能很傻,但是我被困住了。
我有一个类似这样的EF6表EFTable
namespace Database.Models
{
[Table(Name = "EFTable")]
public class EFTable
{
[Column(IsPrimaryKey = true)]
[Key]
public int ID { get; set; }
public int Col1 { get; set; }
public int Col2 { get; set; }
.................
...................
}
}
在我的ViewModel中,
public ICollection<EFTable> EFTableToBindWithDataGrid
{
get
{
return efTable;
}
set
{
efTable = value;
RaisePropertyChanged("EFTableToBindWithDataGrid");
}
}
最后,在我的View(xaml)中,我有一个DataGrid
<DataGrid ColumnWidth="*" AutoGenerateColumns="False" ItemsSource="{ Binding Path=EFTableToBindWithDataGrid,Mode=OneWay}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Col1" Binding="{Binding Col1}"/>
<DataGridTextColumn Header="Col2" Binding="{Binding Col2}" />
<!--................-->
<!--#####HERE-->
<DataGridTextColumn Header="ColNotInEFTable" Binding="{Binding ColNotInEFTable}" />
</DataGrid.Columns>
</DataGrid>
让我陈述我的问题
ColNotInEFTable
,但它们不在EFTableToBindWithDataGrid
中(因为EFTable
没有ColNotInEFTable
字段)
预先感谢
答案 0 :(得分:1)
从您的ViewModel
创建一个Model
。
public class ViewModelInvoiceProduct : INotifyPropertyChanged
{
//only the properties in Model that you want to show in DataGrid
//your additional property
private int _CGST;
public int CGST
{
get
{
return _CGST;
}
set
{
_CGST = value;
RaisePropertyChanged("CGST");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
VIEWMODEL :并将AddedInvoiceProductsViewModel
绑定到您的DataGrid
public ICollection<ViewModelInvoiceProduct> AddedInvoiceProductsViewModel {get;set;}
public ICollection<InvoiceProducts> AddedInvoiceProducts
{
get
{
return invoiceProducts;
}
set
{
invoiceProducts = value;
//the idea to populate AddedInvoiceProductsViewModel
foreach(var invoice in invoiceProducts)
{
var temp = new ViewModelInvoiceProduct();
temp.XXX = invoice.XXX;
temp.CGST = 1 + 2;
AddedInvoiceProductsViewModel.Add(temp);
}
}
}
答案 1 :(得分:1)