在空的dataGrid中添加行

坎蒂努

我正在构建MVVM-WPF应用程序。我只有几个可以在其中进行CRUD操作的dataGrid。

现在,我希望dataGrid在开始时始终为空,当然我可以在其中添加行。因此,我可以填充它,但是当我单击“保存”时,什么也不会保存。

为什么?

ViewModel:

public class InvoiceViewModel : ViewModelBase
{
    public Context ctx = new Context();
    public InvoiceViewModel()
    {
        this.Collection = new ObservableCollection<Invoice>();
    }
    private ObservableCollection<Invoice> collection;
    public ObservableCollection<Invoice> Collection
    {
        get
        {
            return collection;
        }
        set
        {
            collection = value;
            OnPropertyChanged("Collection");
        }
    }
    private Invoice _selected;
    public Invoice Selected
    {
        get
        {
            return _selected;
        }
        set
        {
            _selected = value;
            OnPropertyChanged("Selected");
        }
    }
    private void Get()
    {
        ctx.Invoices.ToList().ForEach(invoice => ctx.Invoices.Local.Add(invoice));;
        Collection = ctx.Invoices.Local;
    }
    private void Save()
    {
        foreach (Invoice item in Collection)
        {
            if (ctx.Entry(item).State == System.Data.Entity.EntityState.Added)
            {
                ctx.Invoices.Add(item);
            }
        }
        ctx.SaveChanges();
    }
    private void Delete()
    {
        var id = Selected;
        var invoice = (from i in ctx.Invoices
                    where i.idInvoice == id.idInvoice
                    select i).SingleOrDefault();
        Collection.Remove(invoice);
    }

    #region "Command"
    // private ICommand getCommand;
    private ICommand saveCommand;
    private ICommand removeCommand;

    /*public ICommand GetCommand
    {
        get
        {
            return getCommand ?? (getCommand = new RelayCommand(p => this.Get(), p => this.CanGet()));
        }
    }
    private bool CanGet()
    {
        return true;
    }*/
    public ICommand SaveCommand
    {
        get
        {
            return saveCommand ?? (saveCommand = new RelayCommand(p => this.Save(), p => this.CanSave()));
        }
    }
    private bool CanSave()
    {
        return true;
    }
    public ICommand DeleteCommand
    {
        get
        {
            return removeCommand ?? (removeCommand = new RelayCommand(p => this.Delete(), p => this.CanDelete()));
        }
    }
    public bool CanDelete()
    {
        if (Selected != null)
            return true;
        else
            return false;
    }
    #endregion
}

看法:

<Page.Resources>
    <local:InvoiceViewModel x:Key="invoice" />
    <local:ShopViewModel x:Key="shop" />
    <local:SupplierViewModel x:Key="supplier" />
    <local:ProductViewModel x:Key="product" />
    <DataTemplate x:Key="ProductDataTemplate">
        <TextBlock Text="{Binding product}" />
    </DataTemplate>
</Page.Resources>
<DataGrid x:Name="dataGridInvoice"
          Margin="5"
          Grid.Row="1"
          ItemsSource="{Binding Collection}"
          AutoGenerateColumns="False"
          SelectedItem="{Binding Selected, Mode=TwoWay}"
          SelectionMode="Extended"
          SelectionUnit="FullRow">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="dataGridTextColumn"
                            Header="Supplier Invoice Nb"
                            Width="*" />
        <DataGridComboBoxColumn Header="Ref Supplier"
                                ItemsSource="{Binding Products, Source={StaticResource supplier}, Mode=OneWay}"
                                DisplayMemberPath="refsup"
                                SelectedValueBinding="{Binding refSupp}"
                                SelectedValuePath="refsup"
                                Width="*" />
        <DataGridTextColumn Header="Unit"
                            Binding="{Binding unit, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                            Width="*" />
        <DataGridTextColumn Header="Quantity"
                            Binding="{Binding quantity, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                            Width="*" />
        <DataGridTextColumn Header="Prix/MOQ"
                            Binding="{Binding unitPrice, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                            Width="*" />
        <DataGridTextColumn Header="Total Price"
                            Binding="{Binding totalPrice, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
                            Width="*" />
    </DataGrid.Columns>
</DataGrid>
<StackPanel Orientation="Horizontal">
    <Button  x:Name="BtnDelete"
             Content="Delete"
             Command="{Binding DeleteCommand}"
             HorizontalAlignment="Center"
             Margin="100,5,5,5"
             Width="85" />
    <Button  x:Name="BtnAdd"
             Content="Save"
             Command="{Binding SaveCommand}"
             HorizontalAlignment="Center"
             Margin="20,5,5,5"
             Width="85" />
</StackPanel>
绝望

您具有实际上将方法绑定Collection到实体集的缓存本地方法的方法如果没有绑定,则很难保存添加的项目:

private void Get() {
        ctx.Invoices.ToList().ForEach(invoice => ctx.Invoices.Local.Add(invoice));;
        Collection = ctx.Invoices.Local;
}

实际上,可以像这样将所有发票加载并缓存到本地:

private void Get() {
   ctx.Invoices.Load();
   Collection = ctx.Invoices.Local;
}

但是,正如您所说的那样,您首先需要一个空的数据网格(仅用于添加),然后您可以重构该Get方法以接受一个布尔值,该布尔值指示是否应首先从db加载数据:

private void Get(bool loadDataFirst) {
   if(loadDataFirst) ctx.Invoices.Load();
   Collection = ctx.Invoices.Local;
}

现在,通过使用Get不首先加载数据方法,您Collection仍然可以很好地绑定到Local缓存(应该为空)。将新项目添加到后CollectionLocal将自动添加这些项目,并且Save可以调用SaveChanges

private void Save() {
   ctx.SaveChanges();
}

Get方法应在构造函数内部使用,替换this.Collection = new ObservableCollection<Invoice>();如下:

public InvoiceViewModel() {
   Get(false);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

NSUserDefaults在UITableViewController中添加行

来自分类Dev

如何在JTable中动态添加行

来自分类Dev

在TableLayoutPanel中动态添加行

来自分类Dev

在QtableView中添加行信号?

来自分类Dev

添加行中的DataTable HTML新对象[]

来自分类Dev

在Pandas DataFrame中向组添加行

来自分类Dev

如何在C#WPF中向Datagrid添加行

来自分类Dev

在HTML texarea中添加行

来自分类Dev

在onCreate()函数中添加行

来自分类Dev

如何在Bootstrap中动态添加行

来自分类Dev

Javascript在html表中添加行

来自分类Dev

按下键在datagridview中添加行

来自分类Dev

在Matlab中以相等间隔添加行

来自分类Dev

如何在段落中添加行号?

来自分类Dev

在WPF中向DataGrid添加行?

来自分类Dev

使用AbstractTableModel在Jtable中添加行

来自分类Dev

在熊猫数据框中添加行移位

来自分类Dev

如何在UWP中向Datagrid动态添加行?

来自分类Dev

在C中的文件中添加行号

来自分类Dev

Perl在begininning中添加行

来自分类Dev

使用Sub向DataGrid添加行

来自分类Dev

在HTML texarea中添加行

来自分类Dev

在onCreate()函数中添加行

来自分类Dev

在JqueryDatatables中添加行ID

来自分类Dev

在脚本中添加行的问题

来自分类Dev

在段落中添加行号

来自分类Dev

在datagrid中添加行无法按预期的方式运行mvvm

来自分类Dev

在查询中添加行号

来自分类Dev

在R中的Scatterplot中添加行