如何使用实体框架刷新 WPF 中的数据网格



我是编程的初学者。我用C#开发了一个WPF应用程序,并使用了实体框架和Devexpress组件。我有一个网格控制组件dgv_SupportComponent。我想在单击btn_Void时刷新dgv_SupportComponent

XAML 标记为:

<Window.Resources>
    <dxcore:EntityCollectionViewSource x:Key="EntityCollectionViewSource" Culture="en-US" ContextType="{x:Type HadishDataModelLayer:HadishDataBaseEntities}" CollectionViewType="{x:Type CollectionView}" Path="vw_SupportComponent">
        <dxcore:DesignDataManager.DesignData>
            <dxcore:DesignDataSettings RowCount="5"/>
        </dxcore:DesignDataManager.DesignData>
    </dxcore:EntityCollectionViewSource>
</Window.Resources>
<Grid Margin="0,0,-0.4,0" >
    <dxg:GridControl x:Name="dgv_SupportComponent" AutoGenerateColumns="None" EnableSmartColumnsGeneration="True" Margin="0,-1,0.4,0.4" SelectionMode="Cell" AllowLiveDataShaping="True" ItemsSource="{Binding Data, Source={StaticResource EntityCollectionViewSource} , UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True }" >
        <dxg:GridControl.View>
            <dxg:TableView x:Name="tlv_support"  ShowTotalSummary="True" AllowEditing="True" AllowPerPixelScrolling="True" RowUpdated="tlv_support_RowUpdated" EditFormPostMode="Immediate" AllowCascadeUpdate="True" AllowGroupSummaryCascadeUpdate="True" ShowAutoFilterRow="True" ShowSearchPanelFindButton="True" ShowSearchPanelMRUButton="True" ShowSearchPanelNavigationButtons="True" SearchPanelAllowFilter="True" SearchColumns="ComponentSt" ShowSearchPanelMode="Never" SearchString="Active" SearchPanelHighlightResults="False" NavigationStyle="Cell" ShowGroupFooters="True" EnableImmediatePosting="True" ShowCriteriaInAutoFilterRow="True" ShowCheckBoxSelectorColumn="True" NewItemRowPosition="Top" IsSynchronizedWithCurrentItem="True" />
        </dxg:GridControl.View>
        <dxg:GridColumn x:Name="CulComponentID" FieldName="ComponentID" IsSmart="True" AllowEditing="True" />
        <dxg:GridColumn FieldName="ComponentName" IsSmart="True" AllowEditing="True" FilterPopupMode="CheckedList" />
        <dxg:GridColumn FieldName="ComponentWeight" IsSmart="True" AllowEditing="True" />
        <dxg:GridColumn FieldName="ComponentWarehouseName" IsSmart="True" />
        <dxg:GridColumn FieldName="ApprovedBy" IsSmart="True"/>
        <dxg:GridColumn FieldName="ComponentWaste" />
        <dxg:GridColumn FieldName="ComponentSt" />
    </dxg:GridControl>
</Grid>

我想在单击btn_Void时刷新数据网格。

此代码已将数据更新为 SQL,但数据网格不会刷新。

我的代码是:

private void btn_Void_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
{
    foreach (int rowHandle in tlv_support.GetSelectedRowHandles())
    {
        int supid = Convert.ToInt32(dgv_SupportComponent.GetCellValue(rowHandle, "ComponentID"));
        db.SPSupportComponentState(supid, HadishLogicLayer.HadishCode.gCompanyCode, false, HadishLogicLayer.HadishCode.gUserID);
    }
    dgv_SupportComponent.RefreshData(); /// this code dose not refresh datagrid 
}

如果你在这里尝试一些MVVM会怎样?

您的网格

<ListView Name="MyListView" ItemsSource="{Binding AllItems}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
            <GridViewColumn Header="Approuved By" DisplayMemberBinding="{Binding Approver}"/>
        </GridView>
    </ListView.View>
</ListView>

按钮

<Button Command="{Binding UpdateDataCommand}" Content="Refresh All" Margin="10" Width="100"/>

视图模型

public abstract class ViewModelBase : INotifyPropertyChanged
{
    protected void RaisePropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

public class Item : ViewModelBase, INotifyPropertyChanged
{
    private string _approver;
    public int Id { get; set; }
    public string Name { get; set; }
    public string Approver
    {
        get { return _approver; }
        set
        {
            if (_approver != value)
            {
                _approver = value;
                RaisePropertyChanged(nameof(Approver));
            }
        }
    }
}
public class MyViewModel : ViewModelBase
{
    public MyViewModel()
    {
        UpdateDataCommand = new RelayCommand(_ => UpdateAll());
    }
    public ObservableCollection<Item> AllItems { get; set; } = new ObservableCollection<Item>();
    public ICommand UpdateDataCommand { get; set; }
    private void UpdateAll()
    {
        //Fetch from DB
        var items = new[]
        {
            new Item {Id=1, Name="Item 1", Approver="Lance"},
            new Item {Id=2, Name="Item 2", Approver="John"}
        };
        AllItems.Clear();
        foreach (var item in items)
        {
            AllItems.Add(item);
        }
    }
}

** RelayCommand ** (归功于 Josh Smith(https://gist.github.com/schuster-rainer/2648922

现在让我们假设您只需要更新所选项目

<Button Command="{Binding UpdateSelectedCommand}" CommandParameter="{Binding ElementName=MyListView, Path=SelectedItem}" Content="Refresh Selected"  Margin="10" Width="100">
    <Button.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=MyListView, Path=SelectedItems.Count}" Value="0">
                    <Setter Property="Button.IsEnabled" Value="False"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

在 VM 构造函数中:

UpdateSelectedCommand = new RelayCommand(selected => UpdateSelected(selected));

UpdateSelected实现:

private void UpdateSelected(object selected)
{
    var selectedItem = selected as Item;
    if (selectedItem != null)
    {
        var item = AllItems.SingleOrDefault(i => i.Id == selectedItem.Id);
        if (item != null)
        {
            item.Approver = "New Approver";
        }
    }
}

瞧!

若要刷新绑定到 EntityCollectionViewSource 的 GridControl,必须创建 EntityCollectionViewSource 的新实例。请查看讨论此主题的如何使用 WPF DXGrid 数据支持票证。

最新更新