如何在 MVVM 中显示 WPF 数据网格中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38876091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:54:23  来源:igfitidea点击:

How to display data in WPF datagrid in MVVM

c#wpfxamlmvvmdatagrid

提问by sujai

My xaml code

我的 xaml 代码

<Window x:Class="SampleWPFApp.View.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewmodel="clr-namespace:SampleWPFApp.ViewModel"
        Title="Window1" Height="500" Width="500">
    <Window.Resources>
        <viewmodel:FirstPageViewModel x:Key="fp"></viewmodel:FirstPageViewModel>
    </Window.Resources>
<Grid>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="75,38,0,0" TextWrapping="Wrap" Text="{Binding FirstName, Source={StaticResource fp}}" VerticalAlignment="Top" Width="120"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="75,79,0,0" TextWrapping="Wrap" Text="{Binding LastName, Source={StaticResource fp}}" VerticalAlignment="Top" Width="120"/>
    <Button Content="Add" HorizontalAlignment="Left" Margin="104,118,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.093,1.636" Command="{Binding acomm, Source={StaticResource fp}}" />
    <DataGrid HorizontalAlignment="Left" Name="mydatagrid" Margin="47,194,0,0" VerticalAlignment="Top" Height="178" Width="385" ItemsSource="{Binding Path=MyDataGrid,Mode=TwoWay,NotifyOnSourceUpdated=True,NotifyOnTargetUpdated=True}" DataContext="{DynamicResource fp} " Loaded="DataGrid_Loaded"/>
</Grid>

My property where grid is bound to in ViewModel,

我在 ViewModel 中绑定网格的属性,

private List<Employee> mysampleGrid;
public List<Employee> MySampleGrid
{
    get
    {
        return mysampleGrid;
    }
    set
    {
        mysampleGrid = value;
        OnPropertyChanged("MySampleGrid");
    }
}

Method called when button is clicked in ViewModel,

在 ViewModel 中单击按钮时调用的方法,

public void AddDataToDb()
{            

    e.FirstName = FirstName;
    e.LastName = LastName;
    context.Employees.Add(e);
    context.SaveChanges();
    this.MySampleGrid = null;

    //Setting List to value from database after inserting into db
    MySampleGrid = context.Employees.Where(x => x.FirstName != null).ToList();

}

But even after setting value of list(which is bound to datagrid) from database grid is not getting updated/refreshed in UI.please help. i have implemented INotifyPropertyChanged interface also.

但即使在设置列表(绑定到数据网格)的值后,数据库网格也没有在 UI 中更新/刷新。请帮忙。我也实现了 INotifyPropertyChanged 接口。

回答by Charles Mager

If you look at your ItemsSourcebinding:

如果你看看你的ItemsSource绑定:

ItemsSource="{Binding Path=MyDataGrid,Mode=TwoWay,NotifyOnSourceUpdated=True,NotifyOnTargetUpdated=True}"

You'll notice that the property you're binding to doesn't exist. This should be MySampleGrid.

您会注意到您绑定的属性不存在。这应该是MySampleGrid

As an aside, most of the contents of the binding can be omitted, this should be all that is required:

顺便说一句,绑定的大部分内容都可以省略,这应该是所需的全部内容:

ItemsSource="{Binding MySampleGrid}"

It would also make sense to set the DataContextof your Window, the child elements will inherit from this and the remaining DataContextattributes can be removed.

设置 的 也是有意义DataContextWindow,子元素将从 this 继承,并且DataContext可以删除剩余的属性。

回答by suulisin

you can do a couple of things to improve your code.

你可以做一些事情来改进你的代码。

  1. First i will suggest you use ObservableCollection since it has Change tracking mechanism.
  2. Also set the DataContext of your grid to your viewmodel instead of individual control's datacontext to your viewmodel
  1. 首先,我建议您使用 ObservableCollection,因为它具有更改跟踪机制。
  2. 还将您的网格的 DataContext 设置为您的视图模型,而不是将单个控件的数据上下文设置为您的视图模型

putting everything together your code show now look like this:

将所有内容放在一起,您的代码显示现在如下所示:

     private ObservableCollection<Employee> mysampleGrid=new ObservableCollection<Employee>();

            public ObservableCollection<Employee> MysampleGrid
            {
                get { return mysampleGrid; }
                set { mysampleGrid= value; }            
            }

public void AddDataToDb()
    {            

        e.FirstName = FirstName;
        e.LastName = LastName;
        context.Employees.Add(e);
        context.SaveChanges();
        this.MySampleGrid = null;

        //Setting List to value from database after inserting into db
        var employees = context.Employees.Where(x => x.FirstName != null).ToList();
        foreach(var employee in employees)
        mysampleGrid.Add(employee);
    }

then finally in your view

然后终于在你看来

<Window x:Class="SampleWPFApp.View.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:viewmodel="clr-namespace:SampleWPFApp.ViewModel"
        Title="Window1" Height="500" Width="500">
    <Window.Resources>
        <viewmodel:FirstPageViewModel x:Key="fp"></viewmodel:FirstPageViewModel>
    </Window.Resources>
<Grid DataContext="{StaticResource fp}">
            <TextBox HorizontalAlignment="Left" Height="23" Margin="75,38,0,0" TextWrapping="Wrap" Text="{Binding FirstName}" VerticalAlignment="Top" Width="120"/>
            <TextBox HorizontalAlignment="Left" Height="23" Margin="75,79,0,0" TextWrapping="Wrap" Text="{Binding LastName}" VerticalAlignment="Top" Width="120"/>
            <Button Content="Add" HorizontalAlignment="Left" Margin="104,118,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="0.093,1.636" Command="{Binding acomm}" />
            <DataGrid HorizontalAlignment="Left" Name="mydatagrid" Margin="47,194,0,0" VerticalAlignment="Top" Height="178" Width="385" ItemsSource="{Binding Path=MysampleGrid,Mode=TwoWay,NotifyOnSourceUpdated=True,NotifyOnTargetUpdated=True}"  Loaded="DataGrid_Loaded"/>

        </Grid>