【发布时间】:2014-09-09 17:47:42
【问题描述】:
我的问题似乎很常见,但是,对于我在此处和其他网站上阅读的所有帖子,我仍然没有找到解决方案。
我有一个相当简单的数据输入 WPF 模块 - 2 个文本框、3 个组合框、1 个数据网格,然后是提交和清除按钮。 (该应用程序/表单用于在会计数据库中创建总分类帐帐户。)我正在使用 PRISM 5 构建我的整个解决方案。(这是我第一次涉足如此复杂的远程事物,目前,它是一个证明——概念的努力。)无论如何,我将所有 WPF 屏幕(用户控件/视图)绑定到适当的视图模型。 ViewModel 反过来通过 EF 6 实体(DB First)从 MSSS db 获取其数据。当用户打开这个特定的 WPF 屏幕时,DataGrid 会显示数据库中的所有现有记录。
除了一个例外,提交(新记录)过程按我的意愿工作:一个新条目被推送到 MSSS 数据库,文本框被清除,ComboBoxes 重置。然而,我想要的是 1)要刷新的 DataGrid,显示新记录,以及 2)在网格中突出显示该新记录。不过,就我的一生而言,我无法让它发挥作用。注意:DataGrid 绑定到数据库中的视图而不是表可能会有所不同。 (同样,当应用首次打开时,DataGrid 会正确显示。)
那么,如何让 DataGrid 更新??????
这是 WPF 视图的(精简的)XAML:
<UserControl x:Class="AcctMappingWpfModule.Views.CreateGLAcctsView"
other namespace declarations...
xmlns:vms="clr-namespace:AcctMappingWpfModule.ViewModels">
<UserControl.DataContext>
<vms:CreateGLAcctsViewModel />
</UserControl.DataContext>
...
<StackPanel ...>
<!-- Layout controls for 2 Text boxes & 3 ComboBoxes -->
...
<!-- Data grid of all Genl Ledger accts -->
<DataGrid x:Name="dgGLAccts"
IsReadOnly="True"
SelectionUnit="FullRow"
...
ItemsSource="{Binding Path=GLAccounts}" />
<WrapPanel >
<!-- Submit & Clear Buttons here -->
</WrapPanel>
</StackPanel>
这是(精简的)ViewModel 代码(省略了 try/catch 块):
namespace AcctMappingWpfModule.ViewModels
{ 公共类 CreateGLAcctsViewModel : BindableBase, ICreateGLAcctsViewModel { 私有 TBLOADEntities 上下文; 私人 int _glAcctID = 0; // 其他私有字段...
// Ctor...
public CreateGLAcctsViewModel( )
{
this.SubmitCommand = new DelegateCommand(OnSubmit);
// Populate ICollectionViews - i.e., properties...
using (context = new TBLOADEntities())
{
// 3 properties behind ComboBoxes populated, then the DataGrid ppt...
List<vwGLAcct> accts = new List<vwGLAcct>();
accts = (from a in context.vwGLAcct select a).ToList<vwGLAcct>();
GLAccounts = CollectionViewSource.GetDefaultView(accts);
}
// Hook up selection change delegates, including...
GLAccounts.CurrentChanged += GLAccounts_CurrentChanged;
}
private void OnSubmit()
{
GLAccount glAcct = new GLAccount()
{
// Various properties set, then...
GlFsAcctTypeComboFK = this.SelectedFSAcctTypeComboID
};
using (context = new TBLOADEntities())
{
context.GlAcct.Add(glAcct);
context.SaveChanges();
// vwGLAcct is the EF entity of the MSSS db view...
List<vwGLAcct> accts = new List<vwGLAcct>();
accts = (from a in context.vwGLAcct select a).ToList<vwGLAcct>();
GLAccounts = CollectionViewSource.GetDefaultView(accts);
SelectedGLAcctID = glAcct.GlAcctID;
GLAccounts.Refresh();
}
}
private void GLAccounts_CurrentChanged(object sender, EventArgs e)
{
vwGLAcct current = GLAccounts.CurrentItem as vwGLAcct;
SelectedGLAcctID = current.GlAcctID;
}
public ICommand SubmitCommand { get; private set; }
public int SelectedGLAcctID
{
get
{ return _glAcctID; }
set
{
SetProperty(ref _glAcctID, value);
}
}
public ICollectionView GLAccounts { get; private set; }
}
}
【问题讨论】:
标签: c# wpf entity-framework mvvm datagrid