在不破坏EF EDMX的情况下在ICollection <model>中绑定附加元素

时间:2018-08-13 14:27:54

标签: c# wpf mvvm entity-framework-6

使用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>


让我陈述我的问题

  1. 我需要绑定计算值ColNotInEFTable,但它们不在EFTableToBindWithDataGrid中(因为EFTable没有ColNotInEFTable字段)
  2. 是否有其他方法可以解决此问题?



预先感谢

2 个答案:

答案 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)

  1. 您可以扩展InvoiceProducts类:将其标记为局部类,并向放置在新文件InvoiceProductsExtended.cs中的局部类中添加新属性
  2. 您还可以将InvoiceProducts替换为新类(包装器或继承者)并绑定到它
  3. 使用绑定转换器从原始属性计算新值