简体   繁体   English

如何使用Entity Framework刷新WPF中的datagrid

[英]How to refresh datagrid in WPF using Entity Framework

I am beginner at programing. 我是编程的初学者。 I developed a WPF application in C# and I use Entity Framework and Devexpress components. 我在C#中开发了一个WPF应用程序,并使用了Entity Framework和Devexpress组件。 I have a GridControl component dgv_SupportComponent . 我有一个GridControl组件dgv_SupportComponent I want to refresh dgv_SupportComponent when I click btn_Void . 我想刷新dgv_SupportComponent当我点击btn_Void

XAML markup is : 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>

I want to refresh datagrid when I click on btn_Void . 我想点击btn_Void时刷新datagrid。

This code has updated data to SQL but datagrid doesn't refresh. 此代码已将数据更新为SQL,但数据网格不会刷新。

My code is : 我的代码是:

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 
}

To refresh GridControl bound to EntityCollectionViewSource, it's necessary to create a new instance of EntityCollectionViewSource. 要刷新绑定到EntityCollectionViewSource的GridControl,必须创建EntityCollectionViewSource的新实例。 Please take a look at the How to work with WPF DXGrid data support ticket where this topic was discussed. 参阅讨论本主题的如何使用WPF DXGrid数据支持服务单。

What if you try some MVVM here? 如果你在这里尝试一些MVVM怎么办?

Your Grid 你的网格

<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 按键

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

ViewModel 视图模型

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 ** (credit to Josh Smith) https://gist.github.com/schuster-rainer/2648922 ** RelayCommand **(归功于Josh Smith) https://gist.github.com/schuster-rainer/2648922

Now let's assume you need to update only the selected item 现在让我们假设您只需要更新所选项目

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

In the VM constructor: 在VM构造函数中:

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

UpdateSelected implementation: 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";
        }
    }
}

Voilà! 瞧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM